Search code examples
javaoperator-precedence

Java Operator Precedence issue for a simple equation


I am trying to implement a simple equation in Java but keep getting the wrong answer apparently due to operator precedence which I am unable to understand.

The equation is:

NewMean = ((N-1) / N) * OldMean + (Xn / N)

in a simple example: N = 6 ; OldMean = 6 ; Xn = 16

So, NewMean = 5/6 * 6 + 16/6 = 7.6667 (Correct answer)

but in code implementation on Java i get wrong answer (2.6665):

double NewMean = ((N-1)/N)*oldMean + (Xn/N);

Solution

  • If the N variable is type int, then ((N-1) / N) is computed using integer division and will round 5/6 down to 0. Change N to a floating-point type and you should get the correct answer.