为什么这个两个双打的简单计算不准确?
可能的重复:
C# (4):双精度减双精度问题 < /p>
86.25 - 86.24 = 0.01
一般来说,我认为上面的说法是正确的,对吗?
但是,如果我输入此内容
double a = 86.24;
double b = 86.25;
double c = b - a;
,我会发现 c = 0.010000000000005116
这是为什么?
Possible Duplicate:
C# (4): double minus double giving precision problems
86.25 - 86.24 = 0.01
generally, I would think the above statement is true right?
However, if I enter this
double a = 86.24;
double b = 86.25;
double c = b - a;
I find that c = 0.010000000000005116
Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浮点数(在本例中为双精度数)无法精确表示十进制值。我建议阅读 David Goldberg 的每个计算机科学家都应该了解浮点知识算术
这适用于所有处理浮点数的语言,无论是 C#、Java、JavaScript……这对于任何使用浮点算术的开发人员来说都是必读的。
正如 VinayC 所建议的,如果您需要精确(且速度较慢)的表示形式,请使用 System.Decimal(在 C# 中又称为十进制)。
Floating point numbers (in this case doubles) cannot represent decimal values exactly. I would recommend reading David Goldberg's What every computer scientist should know about floating-point arithmetic
This applies to all languages that deal with floating point numbers whether it be C#, Java, JavaScript, ... This is essential reading for any developer working with floating point arithmetic.
As VinayC suggests, if you need an exact (and slower) representation, use
System.Decimal
(akadecimal
in C#) instead.Double 是十进制计算的不正确数据类型,请使用 Decimal。主要原因在于 double 存储数字的方式 - 它本质上是十进制数的二进制近似值。
Double is incorrect data type for decimal calculations, use Decimal for that. Main reason lies in how double stores the number - its essentially a binary approximation of the decimal number.