We know that the rand () function can generate random numbers, actually making some kind of transformation based on the seed and returning the generated random number. By default, the seed is 1. Write a small program to test.
Main () {int i,j; for (i=0;i<10;i++) {j=1+ (int) (10.0*rand ()/(rand_max+1.0)), cout<<j<<endl;}} Execute: 9 4 8 8 10 2 4 8 3 6
Each execution result is 9 4 8 8 10 2 4 8 3 6. Without modifying the seed, each run of the program produces the same set of random numbers.
You can invoke Srand (unsigned seed) to modify the seed, so that programs that run two of times will produce a different random number. Time is usually used as a seed, for example:
Srand ((unsigned) time (NULL));
The seeds will change over time, and the probability of random numbers being duplicated is small. But here's a problem: Time returns the number of seconds from 1970.01.01, and if the RAND function is called multiple times within 1s, the resulting data is the same. You can test with the following code.
for (int i = 0;i<1000;++i) std::cout<<randselectquestion (1,1000) << '/t ';
int randselectquestion (int from,int to) {//Select a numeric Srand ((unsigned) time (NULL) between from and to); int span = 0; if (to>from) { span = To-from; Return From+rand ()%span; else {span = from-to; return To+rand ()%span}}
Running the above program, you will find that random numbers are very repetitive. Based on the principle of random number generation, we can make the seed change a bit faster to reduce the repetition probability: Replace time () with clock (), clock----
Calculates the wall-clock time used by the calling process.
Returns the time it takes for a processor to invoke a process or function, in one of the 1-second clocks_per_sec, where Clocks_per_ The SEC's definition in the vs2008 version of the time.h is 1000, which makes seed changes faster and reduces random number repetition probabilities.