Rand () function
#include <stdlib.h>int rand(void);
Rand () is a function that calculates a series of numbers based on a seed, with a particular algorithm. The number returned is between 0 and Rand_max. Rand_max is defined in stdlib.h, at least 32767.
However, this generates pseudo-random numbers because the seeds are set up after the computer is turned on, so this series of numbers are predictable and each time the sequence is equal. To get a real random number, you have to reset the seed.
Srand () function
#include <stdlib.h>void srand(unsigned int seed);
Srand (seed) is a function of the C language that sets the seed of a random number, usually using time as seed, and each time it runs differently, so the resulting random number seed is also different. Srand (Time (NULL))
How to generate random numbers
- Call Srand (Time (NULL)), set the random number seed
- Call Rand () repeatedly to generate a random number
#include <stdlib.h>#include <stdio.h>#include <time.h> void main( void ){ int i; srand((unsigned)time(NULL)); for(i = 0; i < 10; i++) { printf("%d\n", rand()); }}
C language generates random numbers