Random Number generated by C language, with code snippets

Source: Internet
Author: User

To generate a random number in C, you need to call two functions in the stdlib. h header file:

Int rand (void): generates a random integer between 0 and RAND_MAX. (RAND_MAX is defined in stdlib. h and its value is 2147483647)

Void srand (int seed): used to initialize the seed, so that different random numbers are generated each time.

Code snippet:

Copy to ClipboardReference: [www.bkjia.com] # include <stdio. h>
# Include <stdlib. h>

Int main (int argc, char * argv [])
{
Int I;
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand ());
}
Return 0;
}

Code snippet:

Copy to ClipboardReference: [www.bkjia.com]/*
The random numbers generated by the preceding method are different each time, but the order of the random numbers generated during each operation is the same. The reason is that each time the seeds are the same, the same random sequence is generated. Generally, time is used as the seed to ensure that each seed is different. Simple implementation code:
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>

Int main (int argc, char * argv [])
{
Int I;
Srand (int) time (0 ));
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand ());
}

Return 0;
}

Code snippet:

Copy to ClipboardReference: [www.bkjia.com]/*
If you want to generate integers in other ranges, you can use the remainder operation. The following code generates 0 ~ Random numbers between 100:
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>

Int main (int argc, char * argv [])
{
Int I;
Srand (int) time (0 ));
For (I = 0; I <10; I ++ ){
Printf ("% d \ n", rand () %100 );
}

Return 0;
}

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.