How do I write a program to make it run at different random numbers? See the following example:
# I nclude <stdlib. h>
# I nclude <stdio. h>
# I nclude <time. h>
# I nclude <iostream>
Using namespace STD;
Int main (void)
{
Int I;
Time_t t; // based on the time of the computer, the minimum value is 55 ms.
Srand (unsigned) Time (& T ));
Cout <"ten random 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.
The program uses a new function srand.
This function generates a random seed for a random number. The prototype of the function 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.
Both the srand and Rand functions are included in the header file of stdlib. h. The time function is included in time. h.
Since the random numbers produced by Rand are from 0 to rand_max, while rand_max (32767) 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;
Example 1 ~ 255. K = rand () % 244 + 1;
In this way, you can generate random numbers in any range you want.