Seeding the Random Number Generator with srand

Figure 6.9 demonstrates function srand. The program uses the data type unsigned int. An int is represented by at least two bytes, is typically four bytes on 32-bit systems and can be as much as eight bytes on 64-bit systems. An int can have positive and negative values. A variable of type unsigned int is also stored in at least two bytes of memory. A four-byte unsigned int can have only nonnegative values in the range 0–4294967295. Function srand takes an unsigned int value as an argument. The function prototype for the srand function is in header <cstdlib>.


 1   // Fig. 6.9: fig06_09.cpp
 2   // Randomizing the die-rolling program.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <cstdlib> // contains prototypes for functions srand and rand
 6   using namespace std;
 7
 8   int main()
 9   {
10      unsigned int seed = 0; // stores the seed entered by the user
11
12      cout << "Enter seed: ";
13      cin >> seed;
14      srand( seed ); // seed random number generator
15
16      // loop 10 times
17      for ( unsigned int counter = 1; counter <= 10; ++counter )
18      {
19         // pick random number from 1 to 6 and output it
20         cout << setw( 10 ) << ( 1 + rand() % 6 );
21
22         // if counter is divisible by 5, start a new line of output
23         if ( counter % 5 == 0 )
24            cout << endl;
25      } // end for
26   } // end main


Enter seed: 67
         6         1         4         6         2
         1         6         1         6         4



Enter seed: 432
         4         6         3         1         6
         3         1         5         4         2



Enter seed: 67
         6         1         4         6         2
         1         6         1         6         4


Fig. 6.9. Randomizing the die-rolling program.

The program produces a different sequence of random numbers each time it executes, provided that the user enters a different seed. We used the same seed in the first and third sample outputs, so the same series of 10 numbers is displayed in each of those outputs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.138.134