C. generate random number

Source: Internet
Author: User

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  ;} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.