为什么这两个双打的简单计算不准确? [英] Why is this simple calculation of two doubles inaccurate?
问题描述
可能重复:
C#(4):双减双精度问题
86.25 - 86.24 = 0.01
86.25 - 86.24 = 0.01
一般来说,我认为上述陈述是否正确?
generally, I would think the above statement is true right?
但是,如果我输入这个
double a = 86.24;
double b = 86.25;
double c = b - a;
我发现c = 0.010000000000005116
I find that c = 0.010000000000005116
为什么是这样?
推荐答案
浮点数(在这种情况下为双精度)不能完全代表十进制值。我建议阅读David Goldberg的 每个计算机科学家应该了解的有关浮点数算术
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
这适用于处理浮点数的所有语言,无论是C#,Java,JavaScript,...这是必不可少的读取任何使用浮点运算的开发人员。
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.
正如VinayC所建议的,如果您需要一个精确(较慢)的表示,请使用 System.Decimal
(也就是C#中的十进制
)
As VinayC suggests, if you need an exact (and slower) representation, use System.Decimal
(aka decimal
in C#) instead.
这篇关于为什么这两个双打的简单计算不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!