Results 1 to 4 of 4
  1. #1
    Dankaru is offline Member
    Join Date
    Nov 2012
    Posts
    4
    Rep Power
    0

    Default 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. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default 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. #3
    Dankaru is offline Member
    Join Date
    Nov 2012
    Posts
    4
    Rep Power
    0

    Default Re: Calculating percent

    That makes sense now, thank you.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 2
    Last Post: 10-25-2011, 11:26 PM
  2. need help with calculating something
    By mikec420 in forum New To Java
    Replies: 13
    Last Post: 09-29-2011, 10:14 PM
  3. passing percent to public int method
    By BillyB in forum New To Java
    Replies: 3
    Last Post: 02-04-2011, 07:08 AM
  4. calculating the hypotenuse
    By Latanyar in forum New To Java
    Replies: 6
    Last Post: 10-12-2010, 10:20 AM
  5. calculating with dates
    By hannes in forum New To Java
    Replies: 1
    Last Post: 01-14-2010, 09:22 PM

Posting Permissions

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