3

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;
Paul R
  • 208,748
  • 37
  • 389
  • 560
David Da Silva Contín
  • 1,051
  • 2
  • 10
  • 20

1 Answers1

5

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560