在C#中,为什么舍入数学函数Floor、Ceiling和Round不返回
int
?考虑到函数结果总是整数,为什么要返回float
、double
或decimal
呢?double
的范围为±5.0 × 10−324 到 ±1.7 × 10308,而long
的范围为–9,223,372,036,854,775,808到9,223,372,036,854,775,807。不幸的是,并非所有整数浮点值都能由整数表示。
例如,1e19
已经超过了64位有符号整数的范围。
(long)Math.Round(1e19) == -9223372036854775808L // WTF?
虽然单参数重载Math.Round(double)
和Math.Round(decimal)
总是返回一个整数值,但是这些重载仍然不能返回整数值类型。
如果你知道传递给函数的值可以表示为整数值类型,那么你可以自己进行强制转换。库不会这样做,因为它需要考虑一般情况。
(double)100000000000000001L == 1e17
(同时 1e17 == 1e17+1
)。 - Antal Spector-ZabuskyThe integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. Note that this method returns a Double instead of an integral type.
那么请注意最后一部分。 - Habib这是为了包含比int范围更大的数字。所以Math.Floor会返回一个double类型,根据大小和开发人员的需要,可以将其转换为int或long类型。 如果你尝试在int范围之外使用Math.Floor,如果Math.Floor返回int类型,它将失败,但它不会,它返回一个double类型,你可以将其转换为long类型。
double d = 4147483647.5678;
long a = (long)Math.Floor(d);
int b = (int)Math.Floor(d);
Console.WriteLine(a);
Console.WriteLine(b);
Math.Round(1E30)
并且它返回一个int
,会发生什么? - Alvin WongMath.Round()
返回与其参数相同类型是有道理的。更好的问题是为什么没有Math.RoundToInt32
或Math.RoundToInt64
、Math.FloorToInt32
和Math.FloorToInt64
函数。 - supercat