尴尬的arc4random结果

Dav*_*tín 3 random objective-c arc4random

我正在使用此代码,其中'length'值为'50'.

newX = (arc4random()%(lenght+1)) - (lenght/2);
newY = (arc4random()%(lenght+1)) - (lenght/2);
NSLog(@"Creature Move X:%f, Y:%f", newX, newY);
Run Code Online (Sandbox Code Playgroud)

但在调试器中我得到的结果如下:

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
Run Code Online (Sandbox Code Playgroud)

怎么了?

newX并且newY是浮点数:

float newX;
float newY;
Run Code Online (Sandbox Code Playgroud)

Pau*_*l R 5

arc4random返回一个unsigned int(可能length也是unsigned).将您的代码更改为例如

newX = (float)((int)(arc4random() % (length + 1))) - (length / 2));
Run Code Online (Sandbox Code Playgroud)

为了避免在减去时溢出.

请注意,我还为结果添加了显式浮点转换,这不是严格必要的,但它使代码更加不言自明.