0
float sum = 0;
for(int i=0;i<3;i++){
   sum = sum+marks[i];   // marks is an integer array
}
return sum/3;

marks array has values 95, 80, 75

I want answer to be 83.333333 but compiler gives me 83.333336

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Sigmax
  • 9
  • 3
  • 1
    https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Federico klez Culloca Jun 15 '20 at 12:37
  • `83.333336` is the decimal representation of the closest `float` value to 83 + 1/3. If you want something closer, use `double`. If you want want something closer than that, maybe `BigDecimal`. If you want an exact representation, use a fraction; i.e print it as `"250 / 3"` – Stephen C Jun 15 '20 at 12:50
  • For example, if you were to compute the above using `double` and the use the formatter `new DecimalFormat("##.######")`, that would give you the number correct to 6 decimal places. But you have to use `double`. – Stephen C Jun 15 '20 at 13:05

0 Answers0