我对使用python while循环打印输出感到困惑

时间:2019-10-10 11:04:44

标签: python

我认为循环应该以打印输出23.1结尾,为什么要在23.0中停止? 23.0仍然会遇到“如果猜测<= x”,不是吗?

我的python版本是2.7

我是一个新学习者,一直呆在这里,希望有人能为我解释一下,非常感谢。

x = 23
epsilon = 0.01
step = 0.1
guess = 0.0

while abs(guess**2-x) >= epsilon:
    if guess <= x:
        guess += step
        print guess
    else:
        break
if abs(guess**2 - x) >= epsilon:
    print 'failed'
else:
    print ('succeeded: ' + str(guess))

1 个答案:

答案 0 :(得分:5)

breakguess时,循环到达23.000000000000057行,并且该循环大于23。您可能会期望它是23.0,但floating point numbers do not produce exact arithmetic