1

I have the above code

private float farenaitCelsiusMath(float f) {

        float result;
        result = (f-1)*(2/3);
        return result;
    }

when i run the app on the emulator it evaluates to 0 whatever value i give to f.

But when the third line to result = (f-1)*2/3; it evaluates correctly.

Why does that happens? Is there sth i should know about arithmetic expressions in java?

Cœur
  • 37,241
  • 25
  • 195
  • 267
tioschi
  • 389
  • 1
  • 3
  • 11

1 Answers1

3

Because (2/3) is INTEGER division, which evaluates to 0 since integer division truncates.

  • (f-1) is FLOAT since f is FLOAT
  • (2/3) is INTEGER value 0 since integer division truncates
  • (f-1)*(2/3) is FLOAT since (f-1) is FLOAT, and value 0 because anything times 0 is 0.

When it's (f-1)*2/3 then it evaluates as

  • (f-1) is FLOAT since f is FLOAT;
  • (f-1)*2 is FLOAT since (f-1) is FLOAT
  • (f-1)*2/3 is FLOAT since (f-1)*2 is FLOAT

To get what you expect, make it (2./3) or (2/3.) -- both are promoted to FLOAT because of the decimal point-- or even better make it explicit with a cast ((float)2/(float)3). This doesn't cost anything at run time, it's all done by the compiler.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
  • dont forget to mention why it works when it isnt in parens. The integers get converted to floats before the multiplication and division in the second version. – Scott M. Feb 03 '12 at 19:40
  • yes that make sense. I didn't know about that. So when they are inside parens they stay integer and the result is also integer which means 0. Correct me if i am wrong. – tioschi Feb 03 '12 at 19:46
  • @Charlie Martin great. Thank you. I get it now. So the best way is to write it (f-1)*(2.0/3.0) – tioschi Feb 03 '12 at 19:48
  • Yeah, I was expanding that as you commented, Scott. @miako, it's not really the parens, it's evaluation order -- plus the rule that arithmetic operation promote to the "bigger" type. Floats are higher, so any float time an integer becomes a float. In your example, (2/3) has been converted to 0 by integer division. Now, in other languages, the result of 2/3 would be a floating point type, the value would be 0.6666666 and change, and you'd get what you expect. – Charlie Martin Feb 03 '12 at 19:50
  • @CharlieMartin So i have to read about the operators order. It's important – tioschi Feb 03 '12 at 19:54
  • @miako, it is, but this is a simple case. What fooled you was that Java integer division returns an integer, not a float. – Charlie Martin Feb 03 '12 at 20:35