Description
Here the role of Srand is very important, the role of Srand () is to initialize the random number seed, the seed pseudo-random number calculation basis,
The same seed, the calculated random number is the same, usually the function is not used to srand () but with Rand (), it is equivalent to call the Srand (1),
This also solves the last semester when I do the final memory game, each time you rerun the program, the resulting random number is the same problem
The value returned by Time (NULL) is the number of seconds since the 1970.1.1 zero, so every moment is different
Code
#include <stdio.h>#include <time.h> //time () #include <stdlib.h> //srand () +rand () intMain () {Srand (Time (NULL));//Generate [A, b] intm = rand ()% a + B;printf("%d\n", m);}The main generation of random numbers, but the RAND () function generates a random number interval of [0,rand_max]//rand_max is at least 32767 (2e15-1), and the values may be different under different conditions//Here The author uses a magnified way to enlarge the interval (code from Rujia)#include <stdio.h>#include <time.h> //time () #include <stdlib.h> //srand () +rand () intn = -, M =100000;//This function is to get the real number within the [0,1] interval, and then expand (n-1) times in the next function to the roundingDoubleRandom () {return(DoubleRAND ()/Rand_max;}intRandomintm) {return(int) (Random () * (M-1) +0.5);}intMain () {Srand (Time (NULL));printf("%d%d\n", N, m); for(inti =0; I < m; i++) {if(rand ()%2==0) {printf("A"); }Else{printf("B"); }intX, Y; for(;;) {X = random (n) +1; Y = Random (n) +1;if(X! = Y) { Break; } }printf("%d%d\n", X, Y); }return 0;}
C + + generates random numbers