Search code examples
javaexpressionarithmetic-expressions

Which is wrong? Java, Maths or Me...?? Confused...!


I've the below SOP:

System.out.println(9 - ((9 / 2) * 2));

From the maths that I learnt in school, it should evaluate to 0.

But I'm getting the output as 1...!!!

I've tried evaluating the same expression in Google the output is 0.

Java evaluates to 1 while according to Maths, it is evaluated to 0. Any explanation?


Solution

  • You're victim of integer division !

    Dividing integers in a computer program requires special care. Some programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.

    Some logic :

    In Java :

    9/2 = 4 
    4*2 = 8
    9-8 = 1
    

    In real life :

    9/2 = 4.5
    4.5*2 = 9
    9-9 = 0
    

    To avoid that you can cast one of the argument to double in your division :

    System.out.println(9 - (((double)9 / 2) * 2));