Search code examples
javaoperatorsoperator-precedence

The precendence of operators in Java is not applied


I have this piece of code and according to this page here The below output should by right give me, 98.24 but this is giving me 68.8, what is that I am missing here?

public class Qn1 
{
    public static void main(String[] args)
    {
       double cel = 36.8;
       double fah = ((9 / 5 )* cel) + 32;
       System.out.println(cel + "deg C =" + fah +" deg F");
    }
}

Solution

  • Use 9.0 / 5 instead of 9 / 5 in bracket.

    9 / 5 is integer division and its value is 1. And hence the result. You just need to make one of the numerator or denominator a double / float value to enforce floating-point division.

    ((9 / 5 ) * cel) + 32  = (1 * 36.8) + 32 = 68.8
    

    And what you need is: -

    ((9.0 / 5 ) * cel) + 32  = (1.8 * 36.8) + 32 = 66.24 + 32 = 98.24