To show that the numbers produced by rand
occur with approximately equal likelihood, Fig. 6.8 simulates 6,000,000 rolls of a die. Each integer in the range 1 to 6 should appear approximately 1,000,000 times. This is confirmed by the program’s output.
1 // Fig. 6.8: fig06_08.cpp
2 // Rolling a six-sided die 6,000,000 times.
3 #include <iostream>
4 #include <iomanip>
5 #include <cstdlib> // contains function prototype for rand
6 using namespace std;
7
8 int main()
9 {
10 unsigned int frequency1 = 0; // count of 1s rolled
11 unsigned int frequency2 = 0; // count of 2s rolled
12 unsigned int frequency3 = 0; // count of 3s rolled
13 unsigned int frequency4 = 0; // count of 4s rolled
14 unsigned int frequency5 = 0; // count of 5s rolled
15 unsigned int frequency6 = 0; // count of 6s rolled
16
17 // summarize results of 6,000,000 rolls of a die
18 for ( unsigned int roll = 1; roll <= 6000000; ++roll )
19 {
20 unsigned int face = 1 + rand() % 6; // random number from 1 to 6
21
22 // determine roll value 1-6 and increment appropriate counter
23 switch ( face )
24 {
25 case 1:
26 ++frequency1; // increment the 1s counter
27 break;
28 case 2:
29 ++frequency2; // increment the 2s counter
30 break;
31 case 3:
32 ++frequency3; // increment the 3s counter
33 break;
34 case 4:
35 ++frequency4; // increment the 4s counter
36 break;
37 case 5:
38 ++frequency5; // increment the 5s counter
39 break;
40 case 6:
41 ++frequency6; // increment the 6s counter
42 break;
43 default: // invalid value
44 cout << "Program should never get here!";
45 } // end switch
46 } // end for
47
48 cout << "Face" << setw( 13 ) << "Frequency" << endl; // output headers
49 cout << " 1" << setw( 13 ) << frequency1
50 << "
2" << setw( 13 ) << frequency2
51 << "
3" << setw( 13 ) << frequency3
52 << "
4" << setw( 13 ) << frequency4
53 << "
5" << setw( 13 ) << frequency5
54 << "
6" << setw( 13 ) << frequency6 << endl;
55 } // end main
Face Frequency
1 999702
2 1000823
3 999378
4 998898
5 1000777
6 1000422
As the output shows, we can simulate the rolling of a six-sided die by scaling and shifting the values produced by rand
. The program should never get to the default
case (lines 43–44) in the switch
structure, because the switch
’s controlling expression (face
) always has values in the range 1–6; however, we provide the default
case as a matter of good practice. After we study arrays in Chapter 7, we show how to replace the entire switch
structure in Fig. 6.8 elegantly with a single-line statement.
Error-Prevention Tip 6.3
Provide a default case in a switch to catch errors even if you are absolutely, positively certain that you have no bugs!