问题描述
在C#中,为什么舍入数学函数Floor,Ceiling和Round不返回int
?考虑到函数的结果将始终是整数,为什么它返回float
,double
或decimal
?
In C#, why don't the rounding math functions Floor, Ceiling and Round return an int
? Considering the result of the function will always be an integer, why does it return a float
, double
or decimal
?
推荐答案
double
的范围为±5.0×10 至±1.7×10 和.不幸的是,并非所有整数浮点值都可以用整数表示.
double
has the range of ±5.0 × 10 to ±1.7 × 10 and long
has the range of –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Unfortunately not all integral floating point values can be represented by an integer.
例如,1e19
已经超出了64位带符号整数的范围.
For example, 1e19
has already exceeded the range of a 64-bit signed integer.
(long)Math.Round(1e19) == -9223372036854775808L // WTF?
虽然单参数重载Math.Round(double)
和Math.Round(decimal)
始终会返回整数值,但这些重载仍然无法返回整数类型.
While it is true that the single-argument overloads Math.Round(double)
and Math.Round(decimal)
will always return an integral value, these overloads still cannot return an integer value type.
如果您知道,传递给函数的值将返回一个可以用整数类型表示的值,则可以自己进行强制转换.该库不会这样做,因为它需要考虑一般情况.
If you know that the value passed to the function will return a value representable by an integer value type, you can cast it yourself. The library won't do that because it needs to consider the general case.
这篇关于Math.Round为什么不返回int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!