C + + generates random numbers

Source: Internet
Author: User

Sometimes, it takes a random number to write a program. We can actually produce different random numbers each time we want, but the computer is not human, it needs to generate random numbers by the corresponding algorithm.

1. Generate Random Numbers

The function rand () that generates a random number is provided in C + +, and rand () returns a random value ranging from 0 to Rand_max. Rand_max is defined in stdlib.h with a value of 2147483647.

The results of the operation are as follows:

It seems to be a good result, but when we run the program multiple times, the results are the same for each run. Thus, such a random number is meaningless.

2. Generate a real random number

Why do the above programs generate the same random number each time? Because a random number seed is required each time a call to Rand () is generated, and when no random number seed is specified, the random number seed always takes 1, which results in the same random number generated each time.

So as long as we set different random number seeds each time, we can generate unpredictable random numbers. We can easily set the time of the system to the seed of random numbers in different times of the computer. In C + +, the seed is set by the function srand (unsigned int seed). Gets the time in the current system that can be used in the time (0), or in times (0), or when (NULL) to return the system (from Midnight 1970.1.1), in seconds.

In this way, the random number generated each time is different.

3. Generate random numbers within the 0~n range

Sometimes we need a random number in the 0~n range, and in the previous example we have generated a random number of 0~rand_max. What can be done to convert it into a random number in the 0~n range?

The answer is: Seek redundancy. Any number to n balance, the rest of the number is not falling in the 0~n it?

C + + generates random numbers

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.