How to create random numbers from 4 to 10

2019-09-05 14:31发布

问题:

How can I create a random number within a range? I tried following code but it didn't accomplish my task.

int fromNumber = 10;
int toNumber = 30;
int randomNumber = (arc4random()%(toNumber-fromNumber))+fromNumber; 

回答1:

There are seven numbers between 4 and 10 inclusive. arc4random_uniform() is recommended over arc4random() for this purpose.

int randomNumber = arc4random_uniform(7) + 4

The more general case is arc4random_uniform(upper_bound - lower_bound + 1) + lower_bound.



回答2:

Update
I was unaware of arc4random_uniform() before so i recommend https://stackoverflow.com/a/18262992/2611613 as the answer. The answer i linked below still has a good explanation of a general approach to this problem without worrying about languages.


Your answer should work. Without knowing what is wrong with what you have i can only guess at the problem.

Currently you have

int randomNumber = ( arc4random() % ( toNumber - fromNumber ) ) + fromNumber; 

This produces a range [from-to) exclusive where you will never get the value toNumber. If you want your random number be able to get include toNumber

int randomNumber = ( arc4random() % ( toNumber - fromNumber + 1 ) ) + fromNumber; 

With this you would get a range [from-to] inclusive.

You might look at https://stackoverflow.com/a/363732/2611613 for a really good explanation of how this works.