How to work out a percentage?

Started by
1 comment, last by one mind 17 years, 5 months ago
Hi, I have written a dice roll progam that rolls a 6 sided dice 1000000 times and i need to work out the percentage each number comes out. For example, the numbers come out: 1 = 166430 0.0% 2 = 166639 0.0% 3 = 167123 0.0% 4 = 166621 0.0% 5 = 166416 0.0% 6 = 166771 0.0% So to work out the percentage 1 comes out, i divide 166430 by 1000000 to get 0.16643 which i could round to 16.64% for my program. However, my program outputs 0.0% Is this a computer arithmetic problem? Here is the code i use to do the calculation: double percent = 167036 / 1000000; but when i ouput percent it equalt 0.0 Any help would be greatly appreciated. Thanks :)
Advertisement
Actual percent would be this:

unsigned int totalRolls = 1000000, rolled1 = 166430;

double percent1 = (double(rolled1) / totalRolls) * 100;

In your algorythm computation is made with integer numbers, because both operands of division are integer numbers. If at least on of them is of floating point number (float or double), then all computation is performed with floating point numbers. So, like in my excample - cast one of them to double and you'll get the desired result.

Great! Thanks :)

This topic is closed to new replies.

Advertisement