Java 上 0.1 到 2 的奇怪循环 [英] Strange loop on Java for 0.1 to 2
问题描述
我尝试从 0.1 循环到 2.0,然后将输出打印到控制台..但我得到了如下奇怪的输出:
<前>0.10.20.300000000000000040.40.50.60.70.79999999999999990.89999999999999990.99999999999999991.09999999999999991.21.31.40000000000000011.50000000000000021.60000000000000031.70000000000000041.80000000000000051.90000000000000062.0000000000000004源代码:
公共类测试{public static void main(String[] a) {双 i = 0.1;而 (i <2.1)System.out.println(i);i+=0.1;}}}
为什么它不打印确切的数字,而不是像 0.79999999999
这样的点?使用 for
而不是 while
也有什么区别,因为我不知道如何进行 0.1 增量?
这是正常的.它是浮点固有的;像 0.3 这样的数字不能以二进制形式存储为精确值,因此您会慢慢累积错误.参考资料:Python 手册、维基百科,普林斯顿CS的技术解释一>.
I tried to loop from 0.1 to 2.0 and then print the output to the console.. But I got strange output like these:
0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 1.0999999999999999 1.2 1.3 1.4000000000000001 1.5000000000000002 1.6000000000000003 1.7000000000000004 1.8000000000000005 1.9000000000000006 2.0000000000000004
Source code:
public class test {
public static void main(String[] a) {
double i = 0.1;
while (i < 2.1)
System.out.println(i);
i+=0.1;
}
}
}
Why it doesn't this print the exact numbers instead of having point like 0.79999999999
?
Also is ther any difference using for
instead of while
, since I dont know how to make 0.1 increment?
This is normal. It's inherent in floating point; numbers like 0.3 can't be stored as exact values in binary, so you get slowly accumulating errors. References: Python manual, Wikipedia, Technical explanation from Princeton CS.
这篇关于Java 上 0.1 到 2 的奇怪循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!