### Can't figure out how to get percentage

My homework assignment is as follows:

write a program that asks the user how many trials they would like to run. Then, simulate the roll of 2 six-sided dice using rand() repeatedly, according to how many trials the user wanted to run. Finally, report the percentage of how many of the trials yielded a given sum for each of the possible sums from 2 to 12.

My program so far:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int diceThrows;
srand( time(NULL) );
int dice;
int counts[13] = {0};
double percentage;

cout << "How many times do you want to throw the dice?" << endl;
cin >> diceThrows;

for (int i = 0; i < diceThrows; i++)
{
dice = (1 + (rand() % 6)) + (1 + (rand() % 6));
counts[dice] = counts[dice] + 1;
cout << dice << endl;
}

for (int count = 1; count <= diceThrows ; count++)
{
percentage = dice / diceThrows;
cout<< percentage <<endl;
}

return 0;
}

I can get the random numbers generated, but percentage is giving me problems. It's returning all zeros.

Your problem is with the line where you are calculating the percentage value:

Your two variables dice and diceThrows are of type int. C++ does the division based on the types used in the division. When both types are of type int, it does integer divison, which gets truncated to the nearest int value. In this case, dividing one int by another that is larger will result in a value of zero. The conversion to type double only occurs when you assign the computed value to the variable percentage.

To fix this, you need to cast at least one of the ints to double. You should cast both values for clarity, but only casting one of them will get you the result you want, which is a floating point division with double precison, though in this case single precision would be more than enough.
Thank you... I got the percentage equation to work :)

My last issue is how to get the equation to be able to count the number of times 7 (for example) is rolled. Let's say 10 dice rolls are performed, and 7 was rolled 3 times in that series, 0.30 would be the percentage of time 7 was rolled.

Thanks :)
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849`` `````` #include #include using namespace std; int countRepeats(int value_array[],int array_size, int value) {// finds out how many times value repeated in the array int count=0; for(int i=0; i< array_size; i++) { if(value_array[i]==value) count++; } return count; } int main() { const int Max_number_of_throws=25; int diceThrows; srand(time(NULL)); int dice; int counts[Max_number_of_throws]={0}; double percentage; cout << "how many times you want to throw the dice? "<< endl; cout << "Maximum number of throws allowed is " <> diceThrows; for(int i=0; i
Oh my... thank you for the help. I really appreciate it :)
Topic archived. No new replies allowed.