FlashpointPrdx
FlashpointPrdx

Reputation: 11

Not getting correct expected output on diceroll

I am currently working on this program to roll 2 dice. My program works however, for some reason my expected output is coming out as 0.000% for all roll sums instead of what it should be. I am sure I am overlooking something but I have no idea what. Any help is much appreciated!

Current Expected

#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>

using namespace std;

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

// array 'expected' contains counts for the expected number of times
// each sum occurs in 36 rolls

int expected[SIZE]= {0,0,1/36,1/18,1/12,1/9,5/36,1/6,5/36,1/9,1/12,1/18,1/36};

int sum [SIZE] = {0};

int die1;
int die2;

srand(static_cast<unsigned>(time(nullptr)));

for (int i = 0; i <=ROLLS; ++i) {
    die1 = 1 + rand() % 6;
    die2 = 1 + rand() % 6;
    sum[die1+die2]++;
}

cout << fixed << showpoint << setprecision(3);

cout << setw(CW) << "Sum" << setw(CW) << "Total"
     << setw(CW) << "Expected" << setw(CW) << "Actual" << endl;

for (int j = 2; j < SIZE; ++j) {
    cout << setw(CW) << j << setw(CW) << sum[j]
         << setw(CW-1) << (100.0 * expected[j] / 36) << '%'
         << setw(CW-1) << (100.0 * sum[j] / ROLLS) << '%' << endl;
}

return 0;
}

Upvotes: 0

Views: 42

Answers (1)

Joel Filho
Joel Filho

Reputation: 1300

The type of expected is int, which means it's an integer. The results of all of your divisions are truncated to the lowest integer, which is always 0.

You need to:

  1. Declare expected as a real number type, such as float or double
  2. Use the correct literals to make the division produce real numbers, e.g. 5.0f/36 or 5.0/36.

Upvotes: 4

Related Questions