Welcome back! The goals of the first lab this quarter are:
rand
, which has this prototype:
int rand();Note that
rand
takes no
parameters and returns an int
. The integer that it returns
will be a random number between 0 and the constant RAND_MAX. In order to use
the function rand
, you need to
#include <cstdlib>
rand
.
cout << "This program prints out 10 random numbers between"; cout << " 0 and " << RAND_MAX << endl; for (i=0; i < 10; i++) { cout << rand() << endl; }Write a program using this code, compile it and run it. Please DO NOT retype the above code - instead copy and paste it into your program. When you're done, print out the source code and the output of your program. You'll have to remember
rand
function to
generat random numbers, not the same ones each time. In fact, a computer
can only generate what are called pseudorandom numbers, or lists of
numbers that appear to be random. In order to inject more apparent randomness
into our list, we must initialize the random-number generator, by
giving it a number to begin with. This number is called a seed, and
we must give the random number generator a different seed each time in order
for it to produce a new sequence.
To initialize the random number generator, we use the function srand
. Here is its prototype:
void srand(unsigned int);The parameter is the seed, and the function returns no value. Like
rand
, the function prototype is
also found in <cstdlib>
.
This initialization should be done exactly one time, before the first
time that the random number generator is called. But before we call
srand
, we need to get our hands on a good value for the seed.
This number must itself be somewhat random.
A great source of seeds which vary is
the computer's clock, which is continually and rapidly changing. To do this,
use the function time
, the prototype for which is found in
<ctime>
. Putting all of this together, to get a
more random sequence
of numbers, we just need to add the following
line to the beginning of our program:
srand(time(0));
Usually when we are using a random number generator in a program, we don't really want a random number between 0 and RAND_MAX. For example, if we want a one-digit number, then we want a random number between 0 and 9. To do this, we can conveniently use the mod operator. This is called scaling. For example, the following line of code will output a random number between 0 and 9:
cout << rand()%10;This technique allows you to generate random integers between 0 and and integer
m
, m
being the scaling factor.
What would you do, however, if you wanted a random number between 1 and 10? There's a trick - just generate a random number between 0 and 9, then add 1 to it. This is known as shifting
a
and b
and outputs it.