To work with random numbers in c++, use the rand() function from the cstdlib library.
The rand() function returns a random number from the range 0 to RAND_MAX (RAND_MAX is the constant defined in cstdlib. The value depends on the version of the library. In standard implementations, this value is greater than or equal to 32767.)
Example.
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
cout << "RAND_MAX: " << RAND_MAX << endl;
cout << "Random number: " << rand() << endl;
return 0;
}
Result.
RAND_MAX: 2147483647
Random number: 1804289383
When the program is restarted, rand () returns the same value.
This is due to the fact that the algorithms for generating random numbers are based on the use of some initial value (seed). To change the sequence of received numbers, you must change this value.
To do this, use the function srand(int seed).
The srand function generates a new sequence of random numbers for each new seed value.
For example, using code snippets
srand(5);
rand();
and
srand(7);
rand();
we will receive two different random numbers.
To automatically change the seed parameter, the system time is often used every time the program is started. To do this, use the time(0) function from the ctime library
For example, the following code generates a new set of random values for the variables a, b, c each time the program is run
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int a,b,c;
srand(time(0));
a=rand();
b=rand();
c=rand();
cout << a << " " << b << " " << c << endl;
return 0;
}
Result.
2091105117 1163084594 1947318401
Very often it is required to generate a number from a segment from 0 to N.
To do this, you can use the operation of finding the remainder of division %. In this case, the expression will have the form
rand()%(N+1)
For example, to obtain a number from a segment from 0 to 9, you can use expression
rand()%10
To obtain a number from a of a segment from a to b, one can use expression
a+rand()%(b-a+1)
For example,
1+rand()%10
returns a value from 1 to 10.
For example, the following code generates a new set of random values for the variables a, b, c from a segment from 15 to 100 each time the program is run
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int a,b,c;
srand(time(0));
a=15+rand()%(100-15+1);
b=15+rand()%(100-15+1);
c=15+rand()%(100-15+1);
cout << "a=" << a << endl;
cout << "b=" << b << endl;
cout << "c=" << c << endl;
return 0;
}
Result.
a=15
b=50
c=21