1. Member
Join Date
Nov 2012
Posts
4
Rep Power
0

## Calculating percent

I have this code:
Java Code:
```System.out.println();
System.out.println("Rolling dice " + rolls + " times...");
System.out.println("Sum      Total       Percent");
System.out.println("---      -----       -------");

for (int i = 2; i < combinationCount; i++)
{
double percent = (combinations[i] / rolls) * 100;
if (combinations[i] != 0)
{
System.out.println(i + "\t   " + combinations[i] + "\t\t" + percent);
}
else
{
continue;
}
}```
When the compiler runs it, i input 10 for rolls, everything comes out perfect except for when it displays the "percent" variable. For some reason it is displaying all the percents as 0.0. Rolls is displayed as 10 in the lines before the loop, and combinations[i] is displayed correctly and with proper elements. I do not understand where the 0.0 is coming from. Any help?

2. ## Re: Calculating percent

You appear to be doing int division meaning you may be dividing an int by an int, and this will always return an int, even if it is placed in a double variable (percent). So if your numerator is smaller than your denominator, then this division will always return zero. One solution is to cast either the numerator or denominator as a double:

Java Code:
`double percent = ((double)combinations[i] / rolls) * 100;`

3. Member
Join Date
Nov 2012
Posts
4
Rep Power
0

## Re: Calculating percent

That makes sense now, thank you.

4. ## Re: Calculating percent

You are quite welcome!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•