为什么System.MidpointRounding.AwayFromZero也圈在这种情况下? [英] Why does System.MidpointRounding.AwayFromZero not round up in this instance?

查看:549
本文介绍了为什么System.MidpointRounding.AwayFromZero也圈在这种情况下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,为什么 System.Math.Round(1.035,2,MidpointRounding.AwayFromZero)收益1.03,而不是1.04?我觉得自己的回答我的问题就在于标示为注意来电者在<一个href="http://msdn.microsoft.com/en-us/library/ef48waz8.aspx">http://msdn.microsoft.com/en-us/library/ef48waz8.aspx,但我不能换行我的头周围的解释。

In .NET, why does System.Math.Round(1.035, 2, MidpointRounding.AwayFromZero) yield 1.03 instead of 1.04? I feel like the answer to my question lies in the section labeled "Note to Callers" at http://msdn.microsoft.com/en-us/library/ef48waz8.aspx, but I'm unable to wrap my head around the explanation.

推荐答案

您的怀疑是完全正确的。数字与小数部分,当前pressed在.NET文字,在默认情况下的双打。甲双(如浮法)是一个十进制值的近似值,而不是一个precise值。在这种情况下,近似曾经如此微乎其微的1.035小了点。如果您使用的是明确的小数。它的工作原理把它写像您期望的:

Your suspicion is exactly right. Numbers with fractional portion, when expressed as literals in .NET, are by default doubles. A double (like a float) is an approximation of a decimal value, not a precise value. In this case, the approximation is ever so vanishingly on the small side of 1.035. If you write it using an explicit Decimal it works as you expect:

Console.WriteLine(Math.Round(1.035m, 2, MidpointRounding.AwayFromZero));
Console.ReadKey();

要理解为什么双打和彩车工作,他们做的样子,想象一下再presenting十进制数的1/3(或二进制,而遭受了同样的问题)。您can't-其转换为0.3333333 ......,这意味着要重新present它准确地将需要的内存是无限的。

To understand why doubles and floats work the way they do, imagine representing the number 1/3 in decimal (or binary, which suffers from the same problem). You can't- it translates to .3333333...., meaning that to represent it accurately would require an infinite amount of memory.

计算机得到这个使用近似左右。我pcisely解释$ P $怎么样,但是我可能搞错了。你可以阅读所有关于它虽然这里: http://en.wikipedia.org/wiki/IEEE_754- 1985年

Computers get around this using approximations. I'd explain precisely how, but I'd probably get it wrong. You can read all about it here though: http://en.wikipedia.org/wiki/IEEE_754-1985

这篇关于为什么System.MidpointRounding.AwayFromZero也圈在这种情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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