Java上的奇怪循环0.1到2 [英] Strange loop on Java for 0.1 to 2
问题描述
我尝试从0.1循环到2.0,然后将输出打印到控制台.但是我得到了如下奇怪的输出:
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
源代码:
public class test {
public static void main(String[] a) {
double i = 0.1;
while (i < 2.1)
System.out.println(i);
i+=0.1;
}
}
}
为什么这样不打印确切的数字而不是像0.79999999999
这样的点?
因为我不知道如何使0.1递增,所以使用for
代替while
有什么区别吗?
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?
推荐答案
这很正常.它在浮点数中是固有的.像0.3这样的数字不能作为精确值存储在二进制文件中,因此您会逐渐积累错误.参考: Python手册,普林斯顿CS的技术解释.
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屋!