我认为循环应该以打印出 23.1 结束,为什么在 23.0 停止? 23.0 还是会遇到“if guess <= 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))
最佳答案
当 guess
为 23.000000000000057
且大于 23
时,循环到达 break
行。您可能希望它是 23.0
但 floating point numbers do not produce exact arithmetic .
关于python - 我对 python while 循环中的打印感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58321452/