Your X
and Y
variables are int
, so Java performs integer division, here when dividing by 6. That is what is dropping the decimal points. Then it's converted to a float
before being assigned to Z
. By the time it gets to Math.round
, the decimal points are already gone.
Try casting X
to float
to force floating point division:
float Z =((float) X + Y)/6;
That will retain the decimal information that Math.round
will use to properly round its input.
An alternative is to specify a float
literal for 6
, which will force the sum of X
and Y
to be cast to float
before the division:
float Z = (X + Y)/6.0f;
It can't just be 6.0
, because that's a double
literal, and the Java compiler will complain about "possible loss of precision" when attempting to assign a double
to a float
.
Here's the relevant quote from the JLS, Section 15.17.2:
Integer division rounds toward 0. That is, the quotient produced for
operands n and d that are integers after binary numeric promotion
(§5.6.2) is an integer value q whose magnitude is as large as possible
while satisfying |d · q| ≤ |n|.