Your variables are X and Y int , so Java does integer division, here when divided by 6. This is what casts decimal points. It then converts to float before assigning Z By the time he reaches Math.round , the decimal points have already disappeared.
Try distinguishing X from float to force floating point division:
float Z =((float) X + Y)/6;
This will save the decimal information that Math.round will use to properly round its input.
An alternative is to specify the float literal for 6 , which will cause the sum of X and Y be different to float before division:
float Z = (X + Y)/6.0f;
It cannot be just 6.0 , because this literal is double , and the Java compiler will complain about a "possible loss of precision" when trying to assign double a float .
Here's the corresponding quote from JLS, section 15.17.2 :
Integer divisions are rounded to zero. That is, the factor created for operands n and d, which are integers after binary numeric advancement (ยง5.6.2), is an integer q whose value satisfies the condition | d ยท q | โค | n |.
source share