To generate a random number, we mainly use two functions: srand and Rand. Header file:
# Include <stdlib. h>
I. Functions
1. srand
VoidSrand (unsignedIntSeed );
Usage: it requires a seed. The seed corresponds to a random number. If the same seed is used, the Rand () function returns the same random number. To prevent random numbers from being repeated, the system time is often used for initialization. That is, the time function is used to obtain the system time. The returned value is the number of seconds that have elapsed since 00:00:00 GMT, January 1, 1970, and now, the time_t type data is then converted to the (unsigned) type and then passed to the srand function, that is, srand (unsigned) Time (& T) has a common usage, namely: srand (unsigned) Time (null); pass in a null pointer directly, because yourProgramT data is usually not obtained by parameters. Srand (INT) getpid (); Use the program id (getpid () as the initialization seed, which is fixed in the same program.
2. Rand
IntRand (Void);
Generates a pseudo-random number (based on the srand initial Random Number seed) in the range of 0-Rand_max. Rand_max is at least 32767, and my computer is2147483647 (32-bit int type), enough to drink. The modulo can be used to generate random numbers of different ranges, for example:
IntValue = rand () % (MAX +1-Min) + min;
Ii. Example
Generate num random numbers and output them to the file:
Int Genrand ( Long Num, Char * File ){ Long * Dat = (Long *) Malloc (Num * Sizeof ( Long )); Long * P = Dat, I; If (DAT = Null) {printf ( " Malloc error, memory not enough! \ N " ); Exit ( 1 );} Srand (unsigned Int ) Time ( 0 )); For (I = 0 ; I <num; I ++ ) {Dat [I] = Rand ();} /* Save to file */ File * Fp = fopen (file, " W " ); If (FP = Null) {printf ( " Fopen error, can't open file % s! \ N " , File); exit ( 2 );} While (* P) {fprintf (FP, " % LD \ n " , * P ++ );} Free (DAT); fclose (FP ); Return 0 ;}