C-language take random number

Source: Internet
Author: User

The function commonly used to go to the random number is rand ()(in the Stdlib.h header file, different compilers may be different), but actually when using this function it is found that each program runs the same number of times, what is the reason? In fact, it is incorrect to use.

A random number is actually a set of values calculated from the initial data (called a seed) based on a recursive formula, and when the sequence is long enough, this set of values approximates the uniform distribution. In use, if you do not change the initial data each time the calculated number is the same, that is, pseudo-random number. For example:

The program runs for each of these three numbers. That is, pseudo-random number

How can you do this if you want to become a real random number that requires a different seed (that is, initial data) each time you run it? The current use of system time as a seed, because the system time is changing. This requires another function Srand ()(also in the Stdlib.h header file, Different compilers may be different), adding a time.h header file with the current time value as the seed of the srand, which guarantees that a different random number can be taken each time it is run. A change to the previous program would enable the actual random number to be taken.

This will result in a different run every time.

If you want to limit the range rand ()%100, the range is 0-99.

C-language take random number

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.