为什么这个问题的结果是不同的? [英] Why the result is different for this problem?

查看:118
本文介绍了为什么这个问题的结果是不同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个算术问题。

但是结果与正常的数学运算不同,为什么会这样?

  double d1 = 1.000001; 

double d2 = 0.000001;

Console.WriteLine((d1-d2)== 1.0);


解决方案

我猜你在Jon Skeet的Brainteasers页面?答案在同一网站上列出并解释此处



作为参考,这里是从该页复制的答案。






< 3)傻算法


计算机的本意是算术,不是吗?为什么打印出False?

  double d1 = 1.000001;双d2 = 
0.000001; Console.WriteLine((D1-D2)== 1.0);

答案:这里的所有值都以二进制浮点形式存储。虽然1.0可以精确地存储,1.000001实际上存储为
1.0000009999999999177333620536956004798412322998046875,而0.000001实际上存储为
0.000000999999999999999954748111825886258685613938723690807819366455078125。它们之间的差异不完全是1.0,实际上差别也不能完全保存。





I came across this following arithmetic problem.

But the result is different from normal maths operation, Why is it so?

double d1 = 1.000001;

double d2 = 0.000001;

Console.WriteLine((d1-d2)==1.0);

解决方案

I presume you found the question on Jon Skeet's Brainteasers page? The answers are listed and explained here on the same website.

For a matter of reference, here's the answer copied from that page.


3) Silly arithmetic

Computers are meant to be good at arithmetic, aren't they? Why does this print "False"?

double d1 = 1.000001; double d2 =
0.000001; Console.WriteLine((d1-d2)==1.0);

Answer: All the values here are stored as binary floating point. While 1.0 can be stored exactly, 1.000001 is actually stored as 1.0000009999999999177333620536956004798412322998046875, and 0.000001 is actually stored as 0.000000999999999999999954748111825886258685613938723690807819366455078125. The difference between them isn't exactly 1.0, and in fact the difference can't be stored exactly either.


这篇关于为什么这个问题的结果是不同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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