While循环计数不正确 [英] While loop not counting correctly

查看:91
本文介绍了While循环计数不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近两周我一直在学习python编程,到目前为止进展非常好.但是现在我被困住了,似乎找不到答案. 我发现while循环确实很怪异,只是无法缠住我的头.

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

此代码显示:

0
0.2
0.4
...
1.8
2.0

2.0不应该打印,对不对?当x变为2.0时,语句"x< 2"为假,因此循环应退出并且永远不打印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.

现在,对于真正奇怪的部分:它可以与其他数字一起使用. Step_size = 0.4最多可打印1.6,step_size = 0.1最多可打印1.9. 使用"x< 1"作为语句,并且step_size = 0.2也可以.

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.

我想念什么?

最诚挚的问候, 狮子座

Best regards, Leo

我正在使用python 2.7.5和默认的Idle Editior v2.7.5

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

推荐答案

它是浮点算法.在控制台上输出python 3.6

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

这篇关于While循环计数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆