While loop not counting correctly [duplicate]

夙愿已清 提交于 2019-12-11 04:45:28

问题


I've been learning programming in python for the last two weeks and it's going great so far. But now I'm stuck and can't seem to find an answer. I found a really weird behaviour of a while loop, I just can't wrap my head around.

x=0
step_size=0.2

while x<2:
    print x
    x+=step_size

This code prints:

0
0.2
0.4
...
1.8
2.0

2.0 should not be printed, right? When x becomes 2.0 the statement "x<2" is false, therefore the loop should exit and never print 2.0.

And now for the really weird part: it works with other numbers. Step_size=0.4 prints up to 1.6, step_size=0.1 up to 1.9. Using "x<1" as a statement and step_size=0.2 also works.

What am I missing?

Best regards, Leo

Edit: I'm using python 2.7.5 and the default Idle Editior v2.7.5


回答1:


It's floating point arythmetic. Output in console for python 3.6

0
0.2
0.4
0.6000000000000001
0.8
1.0
1.2
1.4
1.5999999999999999
1.7999999999999998
1.9999999999999998


来源:https://stackoverflow.com/questions/53208032/while-loop-not-counting-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!