1. Some programs should not produce the same results each time they execute, such as games and simulations. In this case, random numbers are very useful. The following two functions can be used together to generate a pseudo-random number (pseudo-random number): the random number generated by calculation may be repeated, so it is not a real random number.
Int rand (void );
Void srand (unsigned int seed );
1> Rand returns a pseudo-random number ranging from 0 to rand_max (at least 32767. When it is called repeatedly, the function returns other numbers in this range. To get a pseudo-random number in a smaller range, first modulo the return value of this function based on the size of the required range, and then adjust it by adding or subtracting an offset.
2> to prevent the program from getting the same random number sequence each time it runs, you can call the srand function. It uses its parameter value to initialize the random number generator.
A common technique is to use the daily time as the seed of the random number generator, for example:
Srand (unsigned INT) time (0 ));
2. instance:
Procedure 1:
# Include <stdio. h>
# Include <stdlib. h>
Int main ()
{
Int K;
K = rand ();
Printf ("% d \ n", k );
Return 0;
}
You can compile and run the above Code and find that it does generate a random number, but you will find that the random number is the same every time you run the program. Why? Because the random number is a fixed sequence in the C language, each execution takes the same number.
So how to write a program so that the random numbers generated each time it runs are different? See the following example:
# Include <stdlib. h>
# Include <time. h>
# Include <stdlib. h>
Int main (void)
{
Int I;
Srand (unsigned INT) time (0 ));
Printf ("tenrandom numbers from 0 to 99 \ n ");
For (I = 0; I <10; I ++)
Printf ("% d \ n", Rand () %100 );
Return 0;
}
When you run the program, you will find that the random numbers generated each time are different.
So why is the first program the same and the second program the same?
The second program uses a new function srand, which generates a random seed for a random number. The function prototype is srand (unsigned) Time (null ));
The value of time varies every moment. So the seeds are different, so the random numbers are also different.
Therefore, to generate different random numbers, you must call srand before using Rand.
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;
In this way, you can generate random numbers in any range you want.