1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

doubles & rounding

Discussion in 'Java' started by Prod_gy, Jan 21, 2007.

  1. Prod_gy

    Prod_gy New Member

    Joined:
    Jan 21, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm working on an ASCII version of battleship, and as part of the project, the hit/miss stats have to be printed out at the end. Because this is for a computer science course, my output has to be identical to the required output.

    My program prints this:
    Hit ratio: 66.66666666666667%
    When it should be printing:
    Hit ratio: 66.66666666666666%

    and..
    My Program:
    Hit ratio: 33.333333333333336%
    Required output:
    Hit ratio: 33.33333333333333%

    I'm assuming that this is happening because of the way doubles behave, but I have no idea how I would fix that.
    Here's the code that computes the ratio:

    double ratio = 100.0 * numHit / numFired;
    Where numHit is a double representing the number of missiles that hit
    and numFired is a double representing the number of missiles fired
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    try using long instead of double.
     
  3. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    Long won't get you any decimal places. There are two issues. One is that the accuracy of the operation is constrained by the particular floating-point implementation. The other is a question of adjusting and formatting the results that you get.
     

Share This Page