C language rand () function usage, rand usage
Rand () (Random Number Generation) related function srand () header file # include <stdlib. h> the int rand () (void) function indicates that rand () returns a random value ranging from 0 to RAND_MAX. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, rand () will automatically set the random number seed to 1. For details about random seed, see srand (). The Return Value Returns a random value between 0 and RAND_MAX. RAND_MAX is defined in stdlib. h and its value is 2147483647. Example/* generates a random number ranging from 1 to 10. In this example, no random seed is set. For the complete random number generation, see srand () */# include <stdlib. h> main () {int I, j; for (I = 0; I <10; I ++) {j = 1 + (int) (10.0 * rand () /(RAND_MAX + 1.0); printf ("% d", j );}} run the related function rand header file # include <stdlib. h> define the void srand (unsigned int seed) function. The function description srand () is used to set the random number seed when rand () generates a random number. The seed parameter must be an integer. Generally, the return value of geypid () or time (0) can be used as seed. If the same value is set for each seed, the random values generated by rand () are the same each time. The return value example/* generates a random number ranging from 1 to 10. This example and execution result can be referenced with rand () */# include <time. h> # include <stdlib. h> main () {int I, j; srand (int) time (0); for (I = 0; I <10; I ++) {j = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0); printf ("% d", j );}} run 5 8 8 8 10 2 10 8 9 92 9 7 4 10 3 2 10 8 7