Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section10.14Random seeds
If you have run the code in this chapter a few times, you might have noticed that you are getting the same “random” values every time. That’s not very random!
One of the properties of pseudorandom number generators is that if they start from the same place they will generate the same sequence of values. The starting place is called a seed; by default, C++ uses the same seed every time you run the program.
While you are debugging, it is often helpful to see the same sequence over and over. That way, when you make a change to the program you can compare the output before and after the change.
If you want to choose a different seed for the random number generator, you can use the srand function from the cstdlib library. It takes a single argument, which is an integer between 0 and RAND_MAX .
For many applications, like games, you want to see a different random sequence every time the program runs. A common way to do that is to use a library function like time from the ctime library to generate something reasonably unpredictable and unrepeatable, like the number of seconds on the system clock.
Listing10.14.1.Try this program - it should print a different sequence of numbers each time you run it. If you remove the srand call, it will generate the same sequence each time.
Notice how srand is used once at the start of the program. You generally only want to seed the number generator one time or you will keep resetting the seed and may generate the same "random" number over and over. If you move srand into the loop, that is what you should see happen.
If we wanted to generate a random number between 0 and 12, and we have previously declared int int x = random ();, what should be our next line of code?