Using C to generate random numbers is a common programming function task. Of course, it is not difficult to call two or three functions, but you know what the functions play, and how do they generate random numbers?
Several Concepts
Random Number: pseudo-random numbers are generated in mathematics. Real random numbers are generated using physical methods.
Random Number seed: the random number is generated by arithmetic rules. The random number seed of srand (seed) is different, and the random number of rand () is different. If the random number seed is the same each time, then the value of rand () is the same. To generate a random number, the random seed of srand (seed) must also be random.
Use srand () to generate random Seed
Prototype: void srand (unsigned int seed );
The function is to set the random number seed. To make the random number seed random, the time (NULL) value is usually used as seed.
Use rand () to generate random numbers
Prototype: int rand (void );
The function is to generate a random number. Of course, the random number has a range of 0 ~ Between RAND_MAX, the random number is related to the random number seed. Specifically, when the random number rand () is called, it will execute as follows:
- If the user has previously called srand (seed), he will call srand (seed) again to generate random seed;
- If srand (seed) is not called, srand (1) is automatically called once.
- If the seed of the random number generated by calling srand (seed) is the same (that is, the seed value is the same), the random number generated by rand () is also the same.
Therefore, if you want rand () to generate different values for each call, you need to call srand (seed) once each time, and seed cannot be the same. Here is why time (NULL) is often used to generate random seed.
Time () is used for Random Seed.
Function prototype: time_t time (time_t * timer );
The time () function returns the number of seconds from 00:00:00 to the current time.
This is used in this case: srand (unsigned (time (NULL); for example, 1 ~ A random integer between 10
#include <stdlib.h>#include <time.h>int main(){ srand(time(NULL)); for(int i=0;i < 10;i++) { int randValue=rand()%10; }}
In the above program, note that srand is outside the for loop. If srand is placed in the for loop, the random numbers generated each time are the same.