In C, If You Want To obtain 1 ~ A random number of 10, so most people may think of it through the following code:
Rand () % 10 + 1;
(Although Rand generates a pseudo-random number, I think it is really random here)
But generate 1 ~ Is the probability of 10 the same?
No. Let's analyze the following.
If the maximum value returned by Rand is 105, then the random number obtained using the method above generates 1 ~ 6 is more likely than generating 7 ~ The probability of 10 is high,
See it? Because if the returned value range of the rand function is 0 ~ 99, use the above method to generate 1 ~ The probability of 10 is the same,,
The returned value range of Rand is 0 ~ 105. If Rand returns 100, the value of rand () % 10 + 1 is 1, which indicates that the probability of 1 is greater than that of other numbers,
Generate 1 ~ 6 is a little more likely.
So if you want to make the generated number more random, you can use the following code:
# Include <stdlib. h> # include <stdio. h> int get_rand10 (void) {int value; int max_rand = (rand_max + 1)/10) * 10-1; srand (unsigned INT) Time (null )); do {value = rand ();} while (value> max_rand); Return Value % 10 + 1 ;}
In general, you do not need to use the above method, but the maximum value of the random number to be generated is closer to rand_max, and the above method should be considered.