(Dice Rolling) Write a program that simulates the rolling of two dice. The program should use rand to roll the first die and should use rand again to roll the second die. The sum of the two values should then be calculated. [Note: Each die can show an integer value from 1 to 6, so the sum of the two values will vary from 2 to 12, with 7 being the most frequent sum and 2 and 12 being the least frequent sums.] Figure 6.21 shows the 36 possible combinations of the two dice. Your program should roll the two dice 36,000 times. Use a one-dimensional array to tally the numbers of times each possible sum appears. Print the results in a tabular format. Also, determine if the totals are reasonable (i.e., there are six ways to roll a 7, so approximately one-sixth of all the rolls should be 7).



What will be an ideal response?

```
#include
#include
#include
#include
using namespace std;

int main()
{
const long ROLLS = 36000;
const int SIZE = 13;

// array expected contains counts for the expected
// number of times each sum occurs in 36 rolls of the dice
int expected[ SIZE ] = { 0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 };
int x; // first die
int y; // second die
int sum[ SIZE ] = {};

srand( time( 0 ) );

// roll dice 36,000 times
for ( long i = 1; i <= ROLLS; i++ )
{
x = 1 + rand() % 6;
y = 1 + rand() % 6;
sum[ x + y ]++;
} // end for

cout << setw( 10 ) << "Sum" << setw( 10 ) << "Total" << setw( 10 )
<< "Expected" << setw( 10 ) << "Actual\n" << fixed << showpoint;

// display results of rolling dice
for ( int j = 2; j < SIZE; j++ )
cout << setw( 10 ) << j << setw( 10 ) << sum[ j ]
<< setprecision( 3 ) << setw( 9 )
<< 100.0 * expected[ j ] / 36 << "%" << setprecision( 3 )
<< setw( 9 ) << 100.0 * sum[ j ] / ROLLS << "%\n";
} // end main
```

Computer Science & Information Technology

You might also like to view...

You can import up to three worksheets at a time during an import operation

Indicate whether the statement is true or false

Computer Science & Information Technology

You can set the Office Clipboard to open automatically any time you cut or copy text two items consecutively.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology