Rolling a Six-Sided Die

To demonstrate rand, Fig. 6.7 simulates 20 rolls of a six-sided die and displays the value of each roll. The function prototype for the rand function is in <cstdlib>. To produce integers in the range 0 to 5, we use the modulus operator (%) with rand as follows:

rand() % 6


 1   // Fig. 6.7: fig06_07.cpp
 2   // Shifted, scaled integers produced by 1 + rand() % 6.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <cstdlib> // contains function prototype for rand
 6   using namespace std;
 7
 8   int main()
 9   {
10      // loop 20 times
11      for ( unsigned int counter = 1; counter <= 20; ++counter )
12      {
13         // pick random number from 1 to 6 and output it
14         cout << setw( 10 ) << ( 1 + rand() % 6 );      
15
16         // if counter is divisible by 5, start a new line of output
17         if ( counter % 5 == 0 )
18            cout << endl;
19      } // end for
20   } // end main


         6         6         5         5         6
         5         1         1         5         3
         6         6         2         4         2
         6         2         3         4         1


Fig. 6.7. Shifted, scaled integers produced by 1 + rand() % 6.

This is called scaling. The number 6 is called the scaling factor. We then shift the range of numbers produced by adding 1 to our previous result. Figure 6.7 confirms that the results are in the range 1 to 6. If you execute this program more than once, you’ll see that it produces the same “random” values each time. We’ll show how to fix this in Figure 6.9.

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

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