问题描述
在C#中,Math.Round(2.5)
的结果是2.
In C#, the result of Math.Round(2.5)
is 2.
它应该是 3,不是吗?为什么在 C# 中用 2 代替?
It is supposed to be 3, isn't it? Why is it 2 instead in C#?
推荐答案
首先,这无论如何都不是 C# 错误——而是 .NET 错误.C# 是语言 - 它不决定如何实现 Math.Round
.
Firstly, this wouldn't be a C# bug anyway - it would be a .NET bug. C# is the language - it doesn't decide how Math.Round
is implemented.
其次,不 - 如果您阅读文档,您会看到默认的舍入是舍入到偶数"(银行家的舍入):
And secondly, no - if you read the docs, you'll see that the default rounding is "round to even" (banker's rounding):
返回值
类型:System.Double
最接近a的整数.如果a 的小数部分是一半在两个整数之间,其中之一是偶数和另一个奇数,那么偶数号返回.请注意,这方法返回一个 Double
而不是一个整型.
备注
此方法的行为遵循 IEEE 标准 754,第 4 节.这种四舍五入是有时称为四舍五入到最接近,或银行家的四舍五入.它最小化舍入误差导致始终舍入一个中点值一个方向.
Remarks
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.
您可以使用 Math.Round 应如何舍入中点"noreferrer">重载 需要一个 MidpointRounding
值.有一个带有 MidpointRounding
的重载,对应于每个没有的重载:
You can specify how Math.Round
should round mid-points using an overload which takes a MidpointRounding
value. There's one overload with a MidpointRounding
corresponding to each of the overloads which doesn't have one:
圆形(十进制)
/Round(Decimal, MidpointRounding)
莉>Round(Double)
/Round(Double, MidpointRounding)
莉>Round(Decimal, Int32)
/Round(Decimal, Int32, MidpointRounding)
一个>Round(Double, Int32)
/Round(Double, Int32, MidpointRounding)
一个>
Round(Decimal)
/Round(Decimal, MidpointRounding)
Round(Double)
/Round(Double, MidpointRounding)
Round(Decimal, Int32)
/Round(Decimal, Int32, MidpointRounding)
Round(Double, Int32)
/Round(Double, Int32, MidpointRounding)
这个默认值是否被很好地选择是另一回事.(MidpointRounding
仅在 .NET 2.0 中引入.在那之前,我不确定是否有任何简单的方法来实现所需的行为,而无需自己动手.)特别是,历史表明它不是预期行为 - 在大多数情况下,这是 API 设计中的大罪.我可以理解为什么银行家的舍入很有用……但对许多人来说它仍然是一个惊喜.
Whether this default was well chosen or not is a different matter. (MidpointRounding
was only introduced in .NET 2.0. Before then I'm not sure there was any easy way of implementing the desired behaviour without doing it yourself.) In particular, history has shown that it's not the expected behaviour - and in most cases that's a cardinal sin in API design. I can see why Banker's Rounding is useful... but it's still a surprise to many.
您可能有兴趣查看最近的 Java 等效枚举 (RoundingMode
) 提供更多选项.(它不只是处理中点.)
You may be interested to take a look at the nearest Java equivalent enum (RoundingMode
) which offers even more options. (It doesn't just deal with midpoints.)
这篇关于为什么 Math.Round(2.5) 返回 2 而不是 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!