Detailed explanation of C + + random number (rand and srand) function usage

C + + provides a set of functions to generate and use random numbers. A random number is a value obtained by randomly se...

C + + provides a set of functions to generate and use random numbers. A random number is a value obtained by randomly selecting from a set of possible values. All values in this group have the same chance of being selected.

The C + + library has a function called rand(), which returns a non negative integer every time it is called. To use the rand() function, you must include the cstdlib header file in your program. The following is an example of its usage:

randomNum = rand();

However, the number returned by this function is actually a pseudo-random number. This means that they have the performance and properties of random numbers, but they are not random in fact. They are actually generated by algorithms.

The algorithm requires a starting value, called seed, to generate numbers. If a seed is not given, it will produce the same digital stream each time it runs. The following procedure illustrates this:

//This program demonstrates what happens in C++ if you // try to generate random numbers without setting a "seed". #include <iostream> #include <cstdlib>// Header file needed to use rand using namespace std; int main() { // Generate and printthree random numbers cout << rand() << " "; cout << rand() << " "; cout << rand() << endl ; return 0; }
Output result of the first operation: 41 18467 6334 Output result of the second operation: 41 18467 6334

To get a different stream of random numbers each time you run the program, you must provide a seed for the random number generator to start. In C + +, this is done by calling the srand function.

Before rand is called, the srand function must be called first, and srand is called only once in the whole program.

// This program demonstrates using random numbers when a // "seed" is provided for the random number generator. #include <iostream> #include <cstdlib> // Header file needed to use srand and rand using namespace std; int main() { unsigned seed; // Random generator seed // Get a nseed" value from the user cout << "Enter a seed value: "; cin >> seed; // Set the random generator seed before calling rand() srand(seed); //Now generate and print three random numbers cout << rand() << " "; cout << rand() << " "; cout << rand() << endl; return 0; }
Results of the first operation: Enter a seed value: 19 100 15331 209 Results of the second operation: Enter a seed value: 171 597 10689 28587

In the program, the variable seed created in line 9 to hold the seed is declared as unsigned. This data type holds only nonnegative integers. This is the data type that the srand function expects to receive during the call, so using the unsigned variable type can ensure that negative numbers will not be sent to srand. It can be seen from the output of the program that each time the program runs with different seeds, different random number streams will be generated. However, if you run the program again using 19 or 171 as a seed, you will get exactly the same number as the first time.

In line 12 of the program, use cin to obtain the value of the random number generator seed from the user's input. In fact, another common way to get seed values is to call the time function, which is part of the C + + standard library.

The time function returns the number of seconds elapsed since midnight on January 1, 1970, so it will provide a different seed value each time the program runs. The following program demonstrates the use of the time function. Note that you must pass it a parameter 0 when calling it. At the same time, the program contains a new header file ctime, which is necessary to use the time function.

//This program demonstrates using the C++ time function //to provide a nseed,T for the random number generator. #include <iostream> #include <cstdlib> // Header file needed to use srand and rand #include <ctime> // Header file needed to use time using namespace std; int main() { unsigned seed; // Random generator seed // Use the time function to get a "seed" value for srand seed = time(0); srand(seed); // Now generate and print three random numbers cout << rand() << " " ; cout << rand() << " " ; cout << rand() << endl; return 0; }
Program output results: 2961 21716 181

Limit the range of random numbers
Sometimes programs need a specific range of random numbers. To limit the range of random numbers to integers between 1 and a maximum value max, you can use the following formula:
number = rand() % max + 1;

For example, to generate a random number of 1 ~ 6 to represent the number of dice, you can use the following statement:
dice = rand() % 6 + 1;

Here is a brief introduction to its working principle. The remainder operator (%) can obtain the remainder after integer division. When the positive integer returned by the rand function is divided by 6, the remainder will be a number from 0 to 5. Since the target is a number from 1 to 6, you only need to add 1 to the remainder.

This idea can be extended to random numbers in any range, and its general formula is as follows:
number = (rand()%(maxValue - minValue +1)) + minValue;

In the above formula, minValue is the minimum value in the range and maxValue is the maximum value in the range. For example, to obtain a random number of 10 ~ 18, the following code can be used to assign a value to the variable number:

const int MIN_VALUE = 10; const int MAX_VALUE = 18; number = rand() % (MAX_VALUE - MIN_VALUE + 1) + MIN_VALUE;

In the above code, (MAX_VALUE - MIN_VALUE + 1) is 9, which is the number of integers in the target range. The value returned by the remainder operator (%) is a number from 0 to 8, and then add min to it_ Value (i.e. 10), you can obtain a random number of 10 ~ 18.

Original link: detailed explanation of the usage of C + + random number (rand and srand) functions

5 December 2021, 08:11 | Views: 5908

Add new comment

For adding a comment, please log in
or create account

0 comments