Ok I'm supposed to be writing a program that simulates dice rolling. The program compiles fine, I just don't understand why the output isn't correct. I get no compile errors, it's just it doesn't correctly output any of the percentages. It displays either inf% or nan%. If anyone could provide any assistance I'd appreciate it...
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int rollDice();
int main()
{
srand(time(0));
int RollNum; // number of times to roll dice
int dicerollValues [5000];
float percentage[10] = {0}; // Array for percentages of numbers
int counter[11];
int i, a;
int value;
int rollsRemaining;
//Ask how many times to roll dice
cout << "How many times will the dice roll?";
cin >> RollNum;
rollsRemaining == RollNum;
//Generate that number of random rolls
for (i=0; i <= RollNum; i++)
{
//Call Dice Roll function
dicerollValues[i] = rollDice();
for (value=2 ; value<=12 ; value++)
{
if (dicerollValues[i] == value)
counter[value-2]++;
}
i++;
}
// loop to calculate percentage of the time each value occurs
for (a= 0; a <12; a++)
percentage [a] = (counter[a]/((float)(RollNum)))* 100;
//Display Results
cout << "The dice were rolled " << rollsRemaining << " times." << endl;
cout << "The value 2 came up " << counter [0] << " times or " << percentage[0] << "% of the time." << endl;
cout << "The value 3 came up " << counter [1] << " times or " << percentage[1] << "% of the time." << endl;
cout << "The value 4 came up " << counter [2] << " times or " << percentage[2] << "% of the time." << endl;
cout << "The value 5 came up " << counter [3] << " times or " << percentage[3] << "% of the time." << endl;
cout << "The value 6 came up " << counter [4] << " times or " << percentage[4] << "% of the time." << endl;
cout << "The value 7 came up " << counter [5] << " times or " << percentage[5] << "% of the time." << endl;
cout << "The value 8 came up " << counter [6] << " times or " << percentage[6] << "% of the time." << endl;
cout << "The value 9 came up " << counter [7] << " times or " << percentage[7] << "% of the time." << endl;
cout << "The value 10 came up " << counter [8] << " times or " << percentage[8] << "% of the time." << endl;
cout << "The value 11 came up " << counter [9] << " times or " << percentage[9] << "% of the time." << endl;
cout << "The value 12 came up " << counter [10] << " times or " << percentage[10] << "% of the time." << endl;
return 0;
}
int rollDice()
{
int die1;
int die2;
int total;
die1 = rand( ) % 6 + 1;
die2 = rand( ) % 6 + 1;
total = die1 + die2;
return total;
}
You are rolling the dice RollNum + 1 times because of the loop on line 29. Change <= to <. percentage has only ten elements but on line 42 you are accessing percentage[10] and percentage[11] which are out of bounds.