Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top