为什么 Math.Ceiling 返回 double?
在 C# 中,Math.Ceiling
方法返回一个 double
值。为什么它不返回int
?
In C# the method Math.Ceiling
returns a double
value. Why does it not return int
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
double
的取值范围比int
更大:该标准规定,
double
具有 52 位尾数,这意味着它可以表示最长 52 位的任何整数,而不会损失精度。因此,如果输入足够大,则输出无法容纳在
int
(只有 32 位)中。double
has a greater value range thanint
:That standard says that
double
has a 52-bit mantissa, which means it can represent any integer up to 52 bits long without loss of precision.Therefore if the input is large enough, the output doesn't fit inside an
int
(which only has 32 bits).文档中关于返回值的说明是:
因此,返回值必须是 double,因为 NaN、NegativeInfinity 和 PositiveInfinity 是 Double 的字段。
The documentation says about the return value:
Therefore the return value has to be double since NaN, NegativeInfinity and PositiveInfinity are fields of Double.
Math.Ceiling
可以返回double
或decimal
,具体取决于传入的类型。换句话说,该方法的输出类型匹配输入类型(非常明智)。他们本可以添加第三个重载,该重载接受一个 int 并返回一个 int ,但这没有多大意义 - 该函数总是只返回其输入。
您似乎假设 Math.Ceiling 的目的是将浮点值转换为整数,但这通常不是它的使用方式。
Math.Ceiling
can return either adouble
or adecimal
, depending on the type passed in. In other words, the output type of the method matches the input type (quite sensibly).They could have added a third overload that takes an
int
and returns anint
, but there wouldn't have been much point to this - the function would always just return its input.You seem to be assuming that the purpose of
Math.Ceiling
is to cast a floating-point value to an integer, but that's usually not how it's used.它必须返回 double 才能完整。任何涉及 NaN 的数学运算始终返回 NaN。因此,如果将 NaN 传递给 Ceiling() 函数,则将无法返回 NaN,因为 Int 中没有等效项。另外,考虑到 Double 的范围更广,对于那些超出范围的整数值会返回什么? +/- inf 返回什么?
It has to return double in order to be complete. Any math operation involving a NaN always returns NaN. Thus if you pass a NaN to ceiling() function one would not be able to return NaN, as there is no equivalent in Int. Also given that Double has a wider range what would one return for those out of range integer values ? What does one return for +/- inf ?
因为
double
可以包含比int
或long
更大的数字。同样的原因,没有从double
到int
的隐式转换。Because
double
can contain larger numbers thanint
orlong
. Same reason there's no implicit cast fromdouble
toint
.