I'm trying to get a random number using arc4random between -60 and 60. I generate avnumber between 1 and 120 inclusively, and then subtract 60.
If this is in one line, I get weird results whenever the number is negative.
//Loop illustrates point better.
while (1) {
//Gets garbage numbers approximately half the time (when random1 should be negative)
NSInteger random1 = 1 + (arc4random() %120) - 60;
NSLog (@"random1: %li", random1);
//Essentially same thing, but works fine.
NSInteger random2 = 1 + (arc4random() %120);
NSInteger random3 = random2 - 60;
NSLog (@"random2: %li random3: %li", random2, random3);
}
Why does this happen?