The rand
function returns a
"random" positive integer from 0 to a large value (at least 32,767,
which is defined by macro
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
. . .
srand(time(0)); // Initialize random number generator.
. . .
r = (rand() % 100) + 1; // 0 to 99, adjusted to 1 to 100
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))
The
standard way to start with a different initial value, the seed, is to
use the current time as a seed. Use the 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.
Use the following include files.
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
on terminal window, Dos
window or unix terminals
myapplication 8 a d
on VC++ IDE environment
In VC++ IDE, go to menu
project -> project property ->debugging -> command arguments
then you type
8 a d
you do not need to type the
application name, because VC++ IDE knows the name of the application.
Use space to separate them