Math.Round为什么不返回int? [英] Why doesn't Math.Round return an int?

查看:209
本文介绍了Math.Round为什么不返回int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,为什么舍入数学函数Floor,Ceiling和Round不返回int?考虑到函数的结果将始终是整数,为什么它返回floatdoubledecimal?

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 −324 至±1.7×10 308

double has the range of ±5.0 × 10−324 to ±1.7 × 10308 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆