Strange loop on Java for 0.1 to 2

后端 未结 2 1445
野趣味
野趣味 2020-12-11 13:32

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.7999         


        
相关标签:
2条回答
  • 2020-12-11 14:08

    That's a bug (on your side).

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

    0 讨论(0)
  • 2020-12-11 14:17

    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.

    0 讨论(0)
提交回复
热议问题