尴尬的 arc4 随机结果
我正在使用此代码,其中“长度”值为“50”。
newX = (arc4random()%(lenght+1)) - (lenght/2);
newY = (arc4random()%(lenght+1)) - (lenght/2);
NSLog(@"Creature Move X:%f, Y:%f", newX, newY);
但在调试器中我得到这样的信息:
2012-01-02 21:10:50.794 Kipos[28833:207] Creature Move X:4294967296.000000, Y:4294967296.000000
2012-01-02 21:10:50.896 Kipos[28833:207] Creature Move X:4294967296.000000, Y:12.000000
发生了什么?
newX
和 newY
是浮点数:
float newX;
float newY;
I'm using this code, where 'length' value is '50'.
newX = (arc4random()%(lenght+1)) - (lenght/2);
newY = (arc4random()%(lenght+1)) - (lenght/2);
NSLog(@"Creature Move X:%f, Y:%f", newX, newY);
But in the debugger I get things like:
2012-01-02 21:10:50.794 Kipos[28833:207] Creature Move X:4294967296.000000, Y:4294967296.000000
2012-01-02 21:10:50.896 Kipos[28833:207] Creature Move X:4294967296.000000, Y:12.000000
What is happening?
newX
and newY
are floats:
float newX;
float newY;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
arc4random 返回一个无符号 int(并且可能
length 也是无符号的)。将代码更改为例如
,以避免减法时溢出。
请注意,我还为结果添加了显式浮点转换,这并不是绝对必要的,但它使代码更加不言自明。
arc4random
returns an unsigned int (and presumablylength
is also unsigned). Change your code to e.g.in order to avoid overflow when you subtract.
Note that I have also added an explicit float cast for the result, which is not strictly necessary but it makes the code a little more self-explanatory.