开发者

Is Java Contradicting Itself?

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜