Random Number in C

Source: Internet
Author: User

How to generate random numbers in C language:

 

To obtain a random number in C, the function must be:

Int rand (void );

Void srand (unsigned int n );

 

Note: This header file must be included # include <stdlib. h>

 

The rand () function returns a pseudo-random number (udorandom) between 0 and RAND_MAX ). The RAND_MAX constant is defined in the stdlib. h header file. The value is 32767 or greater.

The srand () function uses the independent variable n as the seed to initialize the random number generator. When the same seed is passed into srand () and then rand () is called, the same random number sequence is generated. Therefore, we can use time as the seed of the srand () function to avoid repeated occurrence. If srand () is not called before calling rand (), the result is the same as that produced by calling srand (1) in advance.

(1) (2)

Int I;

For (I = 0; I <10; I ++) srand (1 );

Printf ("% d \ t", rand () % 10); for (I = 0; I <10; I ++)

Running result: 1 7 4 0 9 4 8 8 2 4 printf ("% d \ t", rand () % 10 );

Running result: Same as (1)

 

(3) (2)

Int I;

Srand (5) srand (unsigned) time (NULL ));

For (I = 0; I <10; I ++) for (I = 0; I <10; I ++)

Printf ("% d \ t", rand () % 10); printf ("% d \ t", rand () % 10 );

Running result: 4 3 5 9 0 0 7 9 2 0 running result:

The results of each running of the program are different, because the start time of the program is different. Note that the header file time. h must be included before using the time () function.

 

Note:

Calculate random numbers within a certain range;

If the random integer is removed between [), evaluate the modulo between the return value of rand () and 10.

 

For [a, B), use:

(Rand () % (B-a) +;

Related Article

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.