How to generate random numbers in C language:
To obtain a random number in C, the function must be:
Int rand (void );
Void srand (unsigned int n );
Note: This header file must be included # include <stdlib. h>
The rand () function returns a pseudo-random number (udorandom) between 0 and RAND_MAX ). The RAND_MAX constant is defined in the stdlib. h header file. The value is 32767 or greater.
The srand () function uses the independent variable n as the seed to initialize the random number generator. When the same seed is passed into srand () and then rand () is called, the same random number sequence is generated. Therefore, we can use time as the seed of the srand () function to avoid repeated occurrence. If srand () is not called before calling rand (), the result is the same as that produced by calling srand (1) in advance.
(1) (2)
Int I;
For (I = 0; I <10; I ++) srand (1 );
Printf ("% d \ t", rand () % 10); for (I = 0; I <10; I ++)
Running result: 1 7 4 0 9 4 8 8 2 4 printf ("% d \ t", rand () % 10 );
Running result: Same as (1)
(3) (2)
Int I;
Srand (5) srand (unsigned) time (NULL ));
For (I = 0; I <10; I ++) for (I = 0; I <10; I ++)
Printf ("% d \ t", rand () % 10); printf ("% d \ t", rand () % 10 );
Running result: 4 3 5 9 0 0 7 9 2 0 running result:
The results of each running of the program are different, because the start time of the program is different. Note that the header file time. h must be included before using the time () function.
Note:
Calculate random numbers within a certain range;
If the random integer is removed between [), evaluate the modulo between the return value of rand () and 10.
For [a, B), use:
(Rand () % (B-a) +;