1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

doubles & rounding

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

  1. Prod_gy

    Prod_gy New Member

    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

    try using long instead of double.
     
  3. DaWei

    DaWei New Member

    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