为什么这个循环永远不会结束? [英] Why does this loop never end?

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

问题描述

可能重复:
在C#中比较双精度值的问题

Possible Duplicate:
problem in comparing double values in C#

我在其他地方读过它,但是真的忘记了答案,所以我再次在这里问.无论您使用任何语言编写代码(我都使用C#,C ++,Java ...对其进行测试),此循环似乎都永无止境:

I've read it elsewhere, but really forget the answer so I ask here again. This loop seems never end regardless you code it in any language (I test it in C#, C++, Java...):

double d = 2.0;
while(d != 0.0){
   d = d - 0.2;
}

推荐答案

浮点计算不是十分精确.您会收到一个表示错误,因为0.2没有作为二进制浮点数的精确表示,因此该值不会精确地等于零.尝试添加调试语句以查看问题:

Floating point calculations are not perfectly precise. You will get a representation error because 0.2 doesn't have an exact representation as a binary floating point number so the value doesn't become exactly equal to zero. Try adding a debug statement to see the problem:

double d = 2.0;
while (d != 0.0)
{
    Console.WriteLine(d);
    d = d - 0.2;
}


2
1,8
1,6
1,4
1,2
1
0,8
0,6
0,4
0,2
2,77555756156289E-16   // Not exactly zero!!
-0,2
-0,4

一种解决方法是使用类型decimal.

One way to solve it is to use the type decimal.

这篇关于为什么这个循环永远不会结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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