Is Java inconsistent?

Should I declare Math.round(1/2) in Java as int or double? If both are accurate, which is more correct?

Also, why does Eclipse tell me Math.round (1/2) = 0.0, and Math.round (0.5) = 1.0?

Any help would be appreciated!

+6
source share
2 answers

The compiler starts by evaluating the expression 1/2. Both of these numbers are integers, so it does integer math. In integers 1 divides by 2 equals 0. Then it translates 0 to double to pass it to Math.round ().

If you need the correct answer, you need to go in two-room numbers: you can do this using 1.0 / 2.0 instead of 1/2.

+14
source

1/2 is 0, because it is an integer expression.

If you want a floating point value, say 1.0/2.0 (or just 1./2 ).

+6
source

Source: https://habr.com/ru/post/897550/


All Articles