Random Number function in C

Source: Internet
Author: User

This note has no technical knowledge. Here, I will only practice some basic concepts.

When we use random numbers, we usually use the rand () provided in the C library, but because of its "pseudo" nature, therefore, to generate a real random sequence, you must understand the concept of "Seed. At the beginning, I didn't know the "Seed. Now I have finally found the answer.

@ The mechanism of the random number generation function rand () (function prototype int rand (void);) is produced by a static global variable, that is, a seed. By default, seed = 1; as follows:

Ststic unsigned long int next = 1; // Seed

Int rand (void)

{

Next = next * 1103515245 + 12345;

Return (unsigned INT) (Next/65536) % 32768; // The visible random number is not greater than 32768;

}

It can be seen that the number generated each time this function is called is of course the same.

@ So there is another second function srand () to reset the seed (). (function prototype void srand (unsigned int seed); to help rand (), but this often does not meet our requirements, because we only change the random number generated by resetting the seed each time, this is often troublesome.

Void srand (unsigned int seed)
{
Next = seed;
}

@ It would be nice if the seed can be automatically reset. This is feasible. Because the clock of a system is constantly changing. Therefore, you can initialize the seed by using a function time () that can get different return values from the system clock.

# Include <time. h>

Srand (unsigned INT) time (0 ))

In this way, different random numbers can be generated with each rand.

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.