为什么Math.Round(2.5)返回2而不是3? [英] Why does Math.Round(2.5) return 2 instead of 3?

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

问题描述

在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 而不是
整数类型。

Return Value
Type: System.Double
The 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.

备注
此方法的行为遵循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 如何使用过载,它需要 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) / Round(Decimal, MidpointRounding)
  • Round(Double) / Round(Double, MidpointRounding)
  • Round(Decimal, Int32) / Round(Decimal, Int32, MidpointRounding)
  • Round(Double, Int32) / Round(Double, Int32, MidpointRounding)

此默认值是否经过适当选择是另一回事。 (<。code> 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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