rand
function returns a "random" positive integer
from 0 to a large value (at least 32,767) every time it is called.
To scale the value into
the range you want, use the mod (%) operator and addition.
For example to generate a random number in the range 1 to 10
and assign it to r:
#include <ctime> // For time() #include <cstdlib> // For srand() and rand() . . . srand(time(0)); // Initialize random number generator. . . . r = (rand() % 10) + 1;
The sequence of numbers returned by rand()
are called random
because they satisfy statistical tests for randomness,
eg, uniform distribution, coorelation between sequential
numbers is zero, no apparent patterns). But of course
they really can't be truly random (whatever that means) because computers are deterministic.
Therefore they are more properly called pseudorandom numbers.
For a given seed (starting value), the sequence of numbers that rand()
returns will always be the same.
Because the starting point for the
pseudorandom sequence can easily be varied (see below) and because the
sequence is very long (perhaps billions before the sequence repeats),
these pseudorandom numbers are as good as random.
Having the same sequence generated each time
can be useful for debugging, but it isn't very useful when you're
actually using the program.
To generate a different random sequence, it's necessary to set the
seed that starts the sequence. The srand()
function
takes a positive integer parameter which tells where to start the sequence.
srand(2345);The above call sets the initial seed to 2345. However, this still isn't very useful. If you want to have what appears to be a truly random sequence each time you run the program, you need to start with a different seed each time.
srand(time(0))
time()
function
as follows:
srand(time(0)); // Initialize random number generator.at the beginning of the program to initialize the random seed.
time(0)
returns the integer number of seconds
from the system clock. This will almost always be a different value.
#include <ctime> // For time() #include <cstdlib> // For srand() and rand()