I need to generate a random number between -170 and 80. I'm not sure how to "ask" xcode to generate a value between certain numbers. Is this right? Please explain.
(arc4random() %251) - 170;
I need to generate a random number between -170 and 80. I'm not sure how to "ask" xcode to generate a value between certain numbers. Is this right? Please explain.
(arc4random() %251) - 170;
You'd normally use arc4random_uniform
to get a number limited to a specific range.
E.g.
u_int32_t randomNumber = arc4random_uniform(250);
// randomNumber is now between 0 and 249 inclusive
If you want that to start at -170 rather than 0 then, as you seem to be aware, you'd subtract that from it:
int correctRangeRandomNumber = (int)randomNumber - 170;
// correctRangeRandomNumber is now between -170 and 79 inclusive
If you want a random number in the closed range up to 80 then you'll want to use 251
rather than 250
as the upper bound, as you seem to be aware.