I'm trying to write a program that simulates the rolling of dice. The program should print out the percentages of each time a 2-12 was rolled. However the issue I'm having is I'm getting nothing but zero for everything when it prints out.Any help would be great.
#include <iostream>
#include <ctime>
#include <iomanip>
#include <cstdlib>
usingnamespace std;
/************************************Rolling Dice Function***************************-*/
int rollDice ( )
{
int die1; // The number after die 1 is rolled
int die2; // The number after die 2 is rolled
int totalDieCount; // The sum of the two die
die1 = rand() % 6 +1;
die2= rand() % 6 + 1;
totalDieCount = die1 + die2;
return totalDieCount;
}
/*-----------------------------------Main Function-------------------------------------*/
int main ()
{
//Declaration statements
int numberOfRolls; // This is the number of rolls of the dice as assigned by the user
int count; // Keeps track of the number of times the die have been rolled in the for loop
int freqTable [13]; // Keeps track of the frequency of die sums
int i; // Keeps track of where we are in the array freqTable
int totalDieCount; // This is the sum of both the die
// Ask the user how many times the dice should be rolled and assign that number to
// the correct variable declaration
cout << "How many times shall we roll the dice? " << endl;
cin >> numberOfRolls;
//Make sure to zero out the array
for (i = 0; i <= 12 ; i++)
{
freqTable [i] = 0;
}
// Start the sequence off at a random value
srand( time(NULL));
// Begin for loop to roll the dice and add the result to the array
for (count = 0; count < numberOfRolls; count++)
{
// Call the function to roll the dice and assign the retun value
totalDieCount = rollDice();
// Increment the result in the frequency table
freqTable [totalDieCount]++;
}
for (int count = 2; count <=12; count++)
{
cout << "A " << count << " occurs " << (float)((freqTable[count] / numberOfRolls) * 100) << "% of the time." << endl;
}
return 0;
}
This is integer division, and numberOfRolls is almost always greater than freqTable[count], thus you get zero. Convert to float before this division, not after.