Sign in to follow this  
one mind

How to work out a percentage?

Recommended Posts

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 :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this