我认为循环应该以打印输出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))
答案 0 :(得分:5)
当break
为guess
时,循环到达23.000000000000057
行,并且该循环大于23
。您可能会期望它是23.0
,但floating point numbers do not produce exact arithmetic。