Awkward arc4random results

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;

Upvotes: 3

Views: 593

Answers (1)

Paul R
Paul R

Reputation: 212959

arc4random returns an unsigned int (and presumably length is also unsigned). Change your code to e.g.

newX = (float)((int)(arc4random() % (length + 1))) - (length / 2));

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.

Upvotes: 5

Related Questions