Java 是否自相矛盾?
我应该在 Java 中将 Math.round(1/2)
声明为 int 或 double 吗?如果两者都好,哪个更正确?
另外,为什么 Eclipse 告诉我 Math.round(1/2) = 0.0,而 Math.round(0.5) = 1.0 ?
任何帮助将不胜感激!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器首先计算表达式 1/2。这两个数字都是整数,因此它进行整数数学运算。在整数中,1 除以 2 得到 0。然后,它将 0 转换为 double,以便将其传递给 Math.round()。
如果你想要一个正确的答案,你需要传入双精度数:你可以使用 1.0/2.0 而不是 1/2 来做到这一点。
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
是 0,因为它是一个整数表达式。如果您想要浮点值,请说
1.0/2.0
(或只是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 just1./2
).