- The standard C library -- cstdlib -- contains
functions for generating pseudo-random numbers.
- Numbers aren't truly random, because they are simply generated with
an algorithm
- A pseudo-random number generation algorithm starts with a value
called a seed value. (If you use the same seed, you get the
same pattern of "random" numbers!)
- In C++ (and C), the functions needed from cstdlib are
rand() and srand()
- srand() is used to seed the random number generator
(and only needs to be called once).
- The seed value could be obtained from user input, but usually
the best way is to use the time value obtained from the computer's
clock, since that will change frequently (like between runs of the
program)
- To get the clock value, call the function time(0) from the
library ctime
Example:
#include <cstdlib> // for srand(), rand()
#include <ctime> // for time()
// ...
srand( time(0) ); // seed the random number generator
- Once the random number generator has been seeded, use the
rand() function to retrieve a random number. The
function takes no parameters, and returns the random number selected:
int r;
r = rand(); // r now contains a random number
// in the range of possible integers
- Since the random number returned could be from a very large range,
sometimes we want to force the number into a smaller range. This can be
done with the modulus operator %. Divide by the size of the range
and take the remainder:
r = rand() % 10; // r will be a random number from 0 through 9
- If we want to have the range of random numbers start somewhere other
than 0, just add an offset (or subtract) to shift the starting point of
the range:
r = rand() % 10 + 1; // a random number from 1 - 10
r = rand() % 10 + 5; // a random number from 5 - 14
- This example shows some
random number generation