C Programming-random, Rand, srand, srandom Functions

Source: Internet
Author: User

When calling the random number function rand (), the actual random number is not absolutely random. It is a series of "pseudo-random numbers" calculated using an algorithm with an initial value, each time rand () is called, a value is taken from this sequence as a random number. The initial value is "random number seed". That is to say, if the random number seed is the same, the random number series is the same.

Srandom (X) is used to initialize the random number generator and set the random number seed. The given X is the random number seed. It can be verified that when you call srandm (x) multiple times, if the value of X is the same, the random number series will be the same. Therefore, if we want to obtain different random number sequences every time we run the program, we should use different seeds to initialize this random number generator. For example, you can use time to initialize it, or getpid () to initialize it with the PID Number of the process. Because the PID Number of each running program is generally different, therefore, different random number sequences can be generated.

Int
Rand (void); // returns a random number ranging from 0 ~ Pow (2, sizeof (INT)-1
Long int random (void); // returns a random number ranging from 0 ~ Pow (2, sizeof (long INT)-1

Void srand (unsigned int seed); // you can specify the seed of the rand function.
Void srandom (unsigned int seed); // you can specify the seed of the random function.

Summary:
The difference between Rand and random is that the return type is different, int and long int (although the effect is the same on a general 32-bit machine)

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.