C ++ generates random numbers
Description
// Srand plays an important role here. srand () serves to initialize the random number seed and calculate the pseudo-random number of the seed,
// If the seeds are the same, the calculated random number is also the same. Generally, instead of srand (), the function uses rand (), which is equivalent to calling srand (1 ),
// This also solves the same problem when I re-run the program when I was playing the last memory game last semester.
// The value returned by time (NULL) is the number of seconds that have elapsed since, so every moment is different.
Code
# Include
# Include
// Time () # include
// Srand () + rand () int main () {srand (time (NULL); // generate [a, B] int m = rand () % a + B; printf ("% d \ n", m);} // The main function is to generate a random number, but the random number range generated by the rand () function is [0, RAND_MAX] // RAND_MAX must be at least 32767 (2e15-1), and the values may be different under different conditions. // here, the author uses the amplification method to enlarge the range (the code is from Liu rujia) # include
# Include
// Time () # include
// Srand () + rand () int n = 100, m = 100000; // This function is a real number within the range [0, 1, in the next function, increase (n-1) times to get the integer double random () {return (double) rand ()/RAND_MAX;} int random (int m) {return (int) (random () * (m-1) + 0.5);} int main () {srand (time (NULL); printf ("% d \ n ", n, m); for (int I = 0; I <m; I ++) {if (rand () % 2 = 0) {printf ("A") ;}else {printf ("B") ;}int X, Y; for (;) {X = random (n) + 1; Y = random (n) + 1; if (X! = Y) {break;} printf ("% d \ n", X, Y);} return 0 ;}