I am using arc4random to generate a rand开发者_高级运维om number. I would like to generate a number between 1-9. How can I exclude 0?
int r = arc4random() % (9);
NSLog(@"Random Number: %d",r);
int r = (arc4random() % 8) + 1
You can use arc4random_uniform()
, as in
arc4random_uniform(9) + 1
Generally, to generate a number between lo
and hi
(inclusive), you use:
arc4random_uniform(hi - lo + 1) + lo
If you don't want to use arc4random_uniform()
and want to stick with arc4random()
, noting that the resulting value from using modulus formula is not uniformly distributed, use
(arc4random() % (hi - lo + 1)) + lo
int r = arc4random() % 8 + 1;
See other answers (e.g., one from me) for why you probably don't want to use %
for this task, and what you should use instead.
You could simply try repeatedly until you get a number in the range you want, throwing out numbers you don't want. This has the fancy name "acceptance-rejection method" in math. It's simple, and it works.
In case you're worried that this could take a long time, in theory it could. But this approach is used all the time in statistical applications. The probability of going through a while-loop N times decreases rapidly as N increases, so the average number of times through the loop is small.
精彩评论