java 为什么 Math.ceil 返回双精度值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7287099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:25:22  来源:igfitidea点击:

Why does Math.ceil return a double?

javadoublelong-integerceil

提问by PengOne

When I call Math.ceil(5.2)the return is the double6.0. My natural inclination was to think that Math.ceil(double a)would return a long. From the documentation:

当我打电话时Math.ceil(5.2),返回的是double6.0. 我自然倾向于认为这Math.ceil(double a)会返回一个long. 从文档:

ceil(double a)

Returns the smallest (closest to negative infinity) doublevalue that is not less than the argument and is equal to a mathematical integer.

ceil(double a)

返回double不小于参数且等于数学整数的最小(最接近负无穷大)值。

But why return a doublerather than a longwhen 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

但是为什么当结果是整数时返回 adouble而不是 along呢?我认为理解其背后的原因可能有助于我更好地理解 Java。它也可能帮助我弄清楚我是否会通过强制转换为 a 给自己带来麻烦long,例如是

long b = (long)Math.ceil(a);

long b = (long)Math.ceil(a);

always what I think it should be? I fear there could be some boundary cases that are problematic.

总是我认为它应该是什么?我担心可能会有一些有问题的边界案例。

采纳答案by Jon Skeet

The range of doubleis greater than that of long. For example:

的范围double大于的范围long。例如:

double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);

What would you expect the last line to do if Math.ceilreturned long?

如果Math.ceil返回,您希望最后一行做long什么?

Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer xwon't be x + 1if you see what I mean.

请注意,在非常大的值(正数或负数)下,数字最终会非常稀疏地分布 - 因此,如果您明白我的意思,则下一个大于整数的整数x将不会x + 1是。

回答by Peter Lawrey

A double can be larger than Long.MAX_VALUE. If you call Math.ceil()on such a value you would expect to return the same value. However if it returned a long, the value would be incorrect.

double 可以大于Long.MAX_VALUE. 如果您调用Math.ceil()这样的值,您会期望返回相同的值。但是,如果它返回 long,则该值将不正确。