Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   doubles & rounding (http://www.go4expert.com/forums/doubles-rounding-t2635/)

Prod_gy 21Jan2007 13:15

doubles & rounding
 
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

pradeep 22Jan2007 10:55

Re: doubles & rounding
 
try using long instead of double.

DaWei 22Jan2007 19:13

Re: doubles & rounding
 
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.


All times are GMT +5.5. The time now is 20:39.