本文介绍了为什么使用double的for循环无法终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在浏览旧的考试题目(目前是单元考试的第一年),我想知道是否有人可以更彻底地解释为什么下面的代表循环当它应该不会结束。为什么会这样呢?我知道它跳过了100.0,因为四舍五入错误什么的,但为什么呢? for(double i = 0.0; i!= 100; i = i +0.1){ System.out .println(ⅰ); 解决方案用二进制表示,很像三分之一不能用十进制表示,所以你不能保证: 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1 因为在二进制文件中: 0.1 =(二进制)0.00011001100110011001100110011001 .......永远 然而,double不能包含无穷的精度,所以,正如我们接近1/3到0.3333333一样,二进制表示也必须接近0.1。 b $ b 扩展小数比喻 在十进制中,您可能会发现 1/3 + 1/3 + 1/3 = 0.333 + 0.333 + 0.333 = 0.999 这是完全一样的问题。它不应该被看作是浮点数的一个弱点,因为我们自己的十进制系统也有同样的困难(但是对于不同的数字,有三位基本系统的人会觉得奇怪,我们努力代表1/3)。这是一个需要注意的问题。 Demo A 现场演示显示了这些错误。 I'm looking through old exam questions (currently first year of uni.) and I'm wondering if someone could explain a bit more thoroughly why the following for loop does not end when it is supposed to. Why does this happen? I understand that it skips 100.0 because of a rounding-error or something, but why? for(double i = 0.0; i != 100; i = i +0.1){ System.out.println(i);} 解决方案 The number 0.1 cannot be exactly represented in binary, much like 1/3 cannot be exactly represented in decimal, as such you cannot guarantee that: 0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1+0.1==1This is because in binary:0.1=(binary)0.00011001100110011001100110011001....... foreverHowever a double cannot contain an infinite precision and so, just as we approximate 1/3 to 0.3333333 so must the binary representation approximate 0.1.Expanded decimal analogyIn decimal you may find that1/3+1/3+1/3=0.333+0.333+0.333=0.999This is exactly the same problem. It should not be seen as a weakness of floating point numbers as our own decimal system has the same difficulties (but for different numbers, someone with a base-3 system would find it strange that we struggled to represent 1/3). It is however an issue to be aware of.DemoA live demo provided by Andrea Ligios shows these errors building up. 这篇关于为什么使用double的for循环无法终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 06:41