Should I declare Math.round(1/2)
in Java to be an int or a double? If both are fine, which is more correct?
Also, why is it that Eclipse is telling me Math.round(1/2) = 0.0, while Math.round(0.5) = 1.0 ?
Any help would be appreciated!
The compiler starts by evaluating the expression 1/2. Both those numbers are integers, so it does integer math. In integers, 1 divided by 2 is 0. Then, it casts the 0 to a double in order to pass it to Math.round().
If you want a correct answer, you need to pass in doubles: you can do this by using 1.0/2.0 instead of 1/2.
1/2
is 0, because it is an integer expression.
If you want the floating point value, say 1.0/2.0
(or just 1./2
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With