Generating random numbers. Functions rand(), srand(), time(). Examples
Contents
- 1. How to generate a random number in C ++? Function rand(). Example
- 2. Function srand(). The purpose. Example
- 3. Function time(). The purpose. A combination of the functions rand(), srand(), time(). Example
- 4. How to generate a random integer within a given range? Example
- 5. Filling a two-dimensional matrix with random integers within the specified limits. Example
- 6. How to generate a random floating point number within the specified limits? Example
- Related topics
Search other websites:
1. How to generate a random number in C ++? Function rand(). Example
C++ provides facilities for generating random numbers. To generate a random number, the rand() function is used, which is located in the stdlib.h library file. The syntax for declaring a function is as follows:
int rand();
The function returns a random integer value that ranges from 0 to 32767.
Example.
#include <iostream> #include <stdlib.h> using namespace std; void main() { // Get a random number int x; x = rand(); cout << "x = " << x << endl; // Get another random number int y; y = rand(); cout << "y = " << y << endl; }
The result of the program
x = 41 y = 18467
⇑
2. Function srand(). The purpose. Example
If you run the program text from p. 1 several times, you will get the same result (the same numbers). This means that the rand() function itself generates the same sequences of numbers. To get different sequences of numbers, you need to combine the rand() function with the srand() function.
The srand() function from the stdlib.h library is intended to set the starting point from which random numbers are generated. The syntax for declaring a function is as follows:
void srand(unsigned int startValue);
where startValue is an integer value that serves as the starting point for generating a sequence of random numbers with the rand() function. By changing the startValue, you can get different sequences of random numbers.
Example.
#include <iostream> #include <stdlib.h> using namespace std; void main() { // Set the starting point for generating the sequence srand(55); // Get a random number int x; x = rand(); cout << "x = " << x << endl; // Get another random number int y; y = rand(); cout << "y = " << y << endl; }
The result of the program
x = 218 y = 9057
⇑
3. Function time(). The purpose. A combination of the functions rand(), srand(), time(). Example
As you can see from the example in p. 2, the sequence of random numbers has changed. If you set a different number in the srand() function instead of 55, you will get another sequence. However, the program text is static and this number will remain unchanged when the program is run multiple times. The result will be the same sequence of random numbers. To avoid this drawback, the start value in the srand() function needs to be constantly changing.
In order to get different initial values in the srand() function, the time() function from the time.h library is used.
If the time() function is called with a NULL parameter, this function will return the number of milliseconds that have passed since January 1, 1970. This means that the number of milliseconds will depend on the time at which the user started the program for execution. And this moment will be different every time.
If these milliseconds are placed in the srand() function as shown below
srand(time(NULL));
then each time the program is run, a new starting point will be created in generating a sequence of numbers with the rand() function. And, as a consequence, different sequences of random numbers will be obtained.
Example. The example demonstrates how to generate a sequence of two random numbers. Each time the program starts, a new sequence will be received.
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; void main() { // Set the starting point for generating the sequence // use function time(NULL) srand(time(NULL)); // Get a random number int x; x = rand(); cout << "x = " << x << endl; // Get another random number int y; y = rand(); cout << "y = " << y << endl; }
The result of the program
x = 19040 y = 24635
⇑
4. How to generate a random integer within a given range? Example
The example shows the GetRandomNumber() function that generates a random number within the specified range.
#include <iostream> #include <stdlib.h> // This is required to call the functions rand(), srand() #include <time.h> // This is required to call the function time() using namespace std; // Function for generating a random integer number within the specified range. // Range of numbers: [min, max] int GetRandomNumber(int min, int max) { // Set the random number generator srand(time(NULL)); // Get a random number - formula int num = min + rand() % (max - min + 1); return num; } void main() { // Using the GetRandomNumber() function int number; number = GetRandomNumber(-10, 10); // The range of numbers: [-10, 10] cout << "number = " << number << endl;; }
⇑
5. Filling a two-dimensional matrix with random integers within the specified limits. Example
Task. Given a two-dimensional matrix of order n (n columns, n rows) of integers. Find the largest of the values of the elements that are located in the filled part of the matrix. The values of the matrix elements are generated randomly and are in the range [-5; +5].
The program text is as follows
#include <iostream> #include <stdlib.h> // This is required to call the functions rand(), srand() #include <time.h> // This is required to call the function time() using namespace std; void main() { // Two-dimensional arrays. // Calculate the maximum element of the bottom of a matrix // 1. Declaring a variables const int MAX_N = 10; // the maximum allowable dimension of the matrix const int MIN_VALUE = -5; // maximum value of matrix elements const int MAX_VALUE = 5; // minimal value int A[MAX_N][MAX_N]; // original matrix int n; // current size of matrix n*n int max; // result - maximum value // 2. Input n cout << "n = "; cin >> n; // 3. Checking n for correctness if ((n <= 1) || (n > MAX_N)) { cout << "Wrong size of array." << endl; return; } // 4. Form matrix A of random numbers, // set the random number generator srand(time(NULL)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // get a random number A[i][j] = MIN_VALUE + rand() % (MAX_VALUE - MIN_VALUE + 1); } // 5. Print array A for checking cout << endl << "Array A:" << endl; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << A[i][j] << '\t'; cout << endl; } // 6. Calculate the maximum value bool f_first = true; // the checkbox of first item for (int i = 0; i < n; i++) // i - rows for (int j = 0; j < i; j++) // j - columns if (f_first) { // the first element is taken as the maximum max = A[i][j]; f_first = false; } else { if (max < A[i][j]) max = A[i][j]; } // 7. Print the result cout << endl << "max = " << max << endl; }
⇑
6. How to generate a random floating point number within the specified limits? Example
The example demonstrates the GetRandomNumberFloat() function that generates a random floating point number within a specified range.
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; // A function that generates a random floating point number with the specified precision // Function gets 3 parameters: // - min - lower limit; // - max - upper limit; // - precision - accuracy, number of characters after the coma. double GetRandomNumberFloat(double min, double max, int precision) { // Set the starting point srand(time(NULL)); double value; // get a random number as an integer with order precision value = rand() % (int)pow(10, precision); // get a real number value = min + (value / pow(10, precision)) * (max - min); return value; } void main() { // Using the GetRandomNumberFloat() Function double number; srand(time(NULL)); // Get a number in the range [0; 2] with precision 2 decimal places number = GetRandomNumberFloat(0, 2, 2); cout << "number = " << number << endl; }
⇑
Related topics
⇑