It is generally used to set random number generation.
srand((unsigned)time( NULL ));
Because the above settings are based on time, the random number is unpredictable!
In fact, this is a pseudo-random number, and the computer can only generate a pseudo-random number (both random and regular). How does this code produce a random number? Let's talk about how it works:
....
(1) first, provide a seed to srand (). It is an unsigned type and its value ranges from 0 ~ 65535
(2 ). then call Rand (), which returns a random number (between 0 and 32767) based on the seed value provided to srand (). # this step is the core, A random seed is a number used to generate a random number.
(3) call Rand () multiple times as needed to continuously obtain new random numbers;
....
The three steps show that the random number is calculated by the random seed according to a certain algorithm. Therefore, if the calculation method is fixed, the random seed must be fixed, then the random number will not change.
For example, compile and run the following program on the same computer and compilation platform:
unsigned int seed = 1;srand(seed);unsigned value = rand();
The random numbers are always the same. After understanding the basic principle, the program is designed.
..........................
Example of random number generation:
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { int len; srand((unsigned)time( NULL )); len = rand(); printf("%d", len); }
Generate 0 ~ Number between 1
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { float len; srand((unsigned)time( NULL )); len = rand()/32767.0; printf("%f", len); }
What random numbers do you want to generate?
Since the random number generated by Rand ranges from 0 to rand_max, while rand_max is a large number, how can we generate a random number from X ~ What about the number of Y?
From X to Y, there is a number of Y-X + 1, so to generate the number from X to Y, you only need to write like this:
k=rand()%(Y-X+1)+X;