在 C# 中将双精度数乘以 100 会导致意外的结果
可能的重复:
C# 数学给出错误的结果!
我的 C# Windows 应用程序项目中有以下代码:
双重测试 = 2.24 * 100;
如果我添加一块手表来测试,人们会期望该值为 224,但实际上是: 224.00000000000003
谁能解释一下额外的 .00000000000003 来自哪里?
Possible Duplicate:
C# Maths gives wrong results!
I have the following code in my C# windows application project:
double test = 2.24 * 100;
If I add a watch to test, one would expect the value to be 224, however it is actually:
224.00000000000003
can anyone explain where the extra .00000000000003 comes from?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,您没有乘以小数 - 您已经将 IEEE 754 浮点数乘以 100。
因为 2.24 不作为 <代码>双。但是,如果您这样做:
它将按照您的预期运行。
Firstly, you haven't multiplied a decimal - you've multiplied an IEEE 754 floating-point number by 100.
Because 2.24 does not exist as a
double
. However, if you do:it will behave as you expect.
这是设计的行为,这就是浮点数的工作原理 - 精度实际上是有限的。请参阅浮点数 - 精度问题
This is behavior by design, this is how floating point numbers work - the precision is actually limited. See Floating Point Numbers - Accuracy Problems
这是一个舍入错误,并非所有数字都可以用
double
精确表示It's a rounding error, not all numbers can be represented exactly in a
double
许多其他人已经解释过这一点,比我更雄辩。尝试使用以下链接了解大小:
简单说明
高级解释
如果这仍然让您摸不着头脑,只需<插入最喜欢的搜索引擎> “每个程序员都应该了解浮点运算”
Many others have explained this already, far more eloquently than I could. Try these links on for size:
Simple explanation
Advanced explanation
If that still leaves you scratching your head, just <insert favourite search engine> for "What every programmer should know about floating-point arithmetic"
您得到结果是因为 2.24 不是一个准确的数字。除了您提供的 2 个之外,还有更重要的数字。我会尝试乘以 100.00,然后仅使用 3 位有效数字对数字进行四舍五入。
我应该澄清一下,您需要使用十进制变量而不是双精度变量。双精度数不能表示精确值。
Your getting the result because 2.24 is not an exact number. There are a more significant figures beyond just the 2 you provided. I would try a multiplication by 100.00 that and then round the number using only 3 significant figures.
I should make the clarification that you need to be using a decmial variable not a double. A double cannot represent an exact value.