How to generate random numbers in C ++: the rand () function, srand () function, and C ++ do not have the built-in random (int number) function.
(1)If you only need to generate a random number without setting a range, you only need to use rand (): rand () returns a random value ranging from 0 to RAND_MAX. The RAND_MAX value is at least 32767.
For example:
Copy codeThe Code is as follows: # include <stdio. h>
# Include <iostream>
Copy codeThe Code is as follows: int _ tmain (int argc, _ TCHAR * argv [])
{
For (int I = 0; I <10; I ++)
Cout <rand () <endl;
}
(2)If you want to randomly generate a number in a certain range,
For example, a random generation of 10 0 ~ Number of 99:Copy codeThe Code is as follows: # include <stdio. h>
# Include <iostream>
Copy codeThe Code is as follows: int _ tmain (int argc, _ TCHAR * argv [])
{
For (int x = 0; x <10; x ++)
Cout <rand () % 100 <"");
}
In short, generate ~ Random Number in the range of B, available:A + rand () % (B-a + 1)
(3)However, when the preceding two examples run multiple times, the output results are still the same as those for the first time. The advantage is that it is easy to debug, but the meaning of random numbers is lost. If you want to generate different random numbers for each run, the srand () function is used. Srand () is used to set the random number seed when rand () generates a random number. Before calling the rand () function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set () during the call, the random seed is set to 1. In the above two examples, because no random number seed is set, each random number seed is automatically set to the same value of 1, which leads to the same random value produced by rand.
Srand () function definition: void srand (unsigned int seed );
Generally, the return value of geypid () or time (0) can be used as seed.
If you use time (0), add the header file # include <time. h>
For example:Copy codeThe Code is as follows: # include <stdio. h>
# Include <time. h>
# Include <iostream>
Int _ tmain (int argc, _ TCHAR * argv [])
{
Srand (unsigned) time (NULL); // srand (unsigned) time (0) srand (int) time (0) can be
For (int I = 0; I <10; I ++)
Cout <rand () <endl;
}
In this way, the results of each running will be different !!