Use C to generate pseudo-random numbers

Source: Internet
Author: User

The example in MSDN.
// Crt_rand.c
// This program seeds the random-number generator
// With the time, then displays 10 random integers.
//
# Include <stdlib. h>
# Include <stdio. h>
# Include <time. h>
Int main (void)
{
Int I;
 
// Seed the random-number generator with current time so that
// The numbers will be different every time we run.
//
Srand (unsigned) time (NULL ));
// Display 10 numbers.
For (I = 0; I <10; I ++)
Printf ("% 6d \ n", rand ());
Printf ("\ n ");
// Usually, you will want to generate a number in a specific range,
// Such as 0 to 100, like this:
{
Int RANGE_MIN = 0;
Int RANGE_MAX = 100;
For (I = 0; I <10; I ++)
{
Int rand100 = (double) rand ()/
(Double) RAND_MAX) * RANGE_MAX + RANGE_MIN );
Printf ("% 6d \ n", rand100 );
}
}
 
We know that the rand () function can be used to generate random numbers, but this is not a real random number, it is a pseudo random number, it is based on a number, we can call it a kind, A coefficient calculated based on a recursive formula. When the number of series is large, it is in line with the normal announcement, which is equivalent to generating a random number, but this is not a real random number, after the computer starts up normally, the value of this seed is fixed, unless you break the system, in order to change the value of this seed,
Rand () returns a random integer between 0 and RAND_MAX.
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. That is, if srand (unsigned) time (NULL) is removed, the random number generated each time is run is the same.

Author: "cainiao changes"

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.