C++ Random numbers
![]()
Why we need them:
Random numbers allow us to play games, model engineering designs and company operations, and a host of other tasks.
The following command provides a random integer between zero and some really large number, and assigns it to the variable randomNumber:
int randomNumber = rand();
The maximum random number can be found by using RAND_MAX, as in:
int biggestDamnRandomNumber = RAND_MAX;
Note that because of the vagarities of integer math, to scale the rand() to some double, we need to use static cast as follows:
double scaledNumber = static_cast<double>(rand())/RAND_MAX; // determines a random number between zero and one
A final function to use when dealing with random numbers in C++ is the "seed" function, which seeds the random number generator using some user-defined integer (meaning that you, the programmer can set it to be whatever you want!):
srand(seed); // here seed is some user-defined variable, you just need this command in a single line, it doesn't equal anything.
Example program that uses a random number:
This is not done yet.