为什么 Math.ceil 返回双精度?
当我调用 Math.ceil(5.2)
时,返回的是 double
6.0
。我的自然倾向是认为 Math.ceil(double a) 会返回一个 long 。从文档中:
ceil(双a)
返回最小(最接近负无穷大)
double
值 不小于参数并且等于数学 整数。
但是,当结果是整数时,为什么要返回 double
而不是 long
呢?我认为理解其背后的原因可能会帮助我更好地理解 Java。它还可以帮助我弄清楚转换为 long
是否会给自己带来麻烦,例如 is
long b = (long)Math.ceil(a);
总是我认为应该的样子?我担心可能存在一些有问题的边界情况。
When I call Math.ceil(5.2)
the return is the double
6.0
. My natural inclination was to think that Math.ceil(double a)
would return a long
. From the documentation:
ceil(double a)
Returns the smallest (closest to negative infinity)
double
value
that is not less than the argument and is equal to a mathematical
integer.
But why return a double
rather than a long
when the result is an integer? I think understanding the reason behind it might help me understand Java a bit better. It also might help me figure out if I'll get myself into trouble by casting to a long
, e.g. is
long b = (long)Math.ceil(a);
always what I think it should be? I fear there could be some boundary cases that are problematic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
double
的范围大于long
的范围。例如:如果
Math.ceil
返回long
,您希望最后一行做什么?请注意,在非常大的值(正数或负数)下,数字最终会分布得非常稀疏 - 因此,下一个大于整数
x
的整数将不会是x + 1
,如果你明白我的意思了。The range of
double
is greater than that oflong
. For example:What would you expect the last line to do if
Math.ceil
returnedlong
?Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer
x
won't bex + 1
if you see what I mean.双精度数可以大于
Long.MAX_VALUE
。如果您对这样的值调用 Math.ceil() ,您会期望返回相同的值。但是,如果它返回 long,则该值将不正确。A double can be larger than
Long.MAX_VALUE
. If you callMath.ceil()
on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.