开发者

Strange loop on Java for 0.1 to 2

开发者 https://www.devze.com 2023-02-18 08:42 出处:网络
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:

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.7999999999999开发者_如何学Go999
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.


That's a bug (on your side).

Do not use floating point numbers until you learn what they are and how they work.

0

精彩评论

暂无评论...
验证码 换一张
取 消