你一直在崩溃吗?我的python代码有什么问题?
我正在学习python,但这段代码一直在破坏我的文本编辑器 谁能告诉我我做错了什么你一直在崩溃吗?我的python代码有什么问题?,python,macos,sublimetext2,Python,Macos,Sublimetext2,我正在学习python,但这段代码一直在破坏我的文本编辑器 谁能告诉我我做错了什么 x = 12 epsilon = 0.01 numGuesses = 0 low = 0.0 high = max(1.0, x) ans = (high + low)/2.0 while abs (ans**2 - x) >= epsilon: print 'low =', low, 'high =', high, 'ans =', ans numGuesses += 1 if
x = 12
epsilon = 0.01
numGuesses = 0
low = 0.0
high = max(1.0, x)
ans = (high + low)/2.0
while abs (ans**2 - x) >= epsilon:
print 'low =', low, 'high =', high, 'ans =', ans
numGuesses += 1
if ans**2 < x:
low = ans
else:
high - ans
ans = (high + low)/2.0
print 'numGuesses =', numGuesses
print ans, 'is close to square root of', x
有什么建议吗?应该改为:
x = 12
epsilon = 0.01
numGuesses = 0
low = 0.0
high = max(1.0, x)
ans = (high + low)/2.0
while abs (ans**2 - x) >= epsilon:
print 'low =', low, 'high =', high, 'ans =', ans
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
print 'numGuesses =', numGuesses
print ans, 'is close to square root of', x
你处于一个无止境的循环中。当您查看此部分时:
while abs(ans**2 - x) >= epsilon:
而absans**2-x始终为24,而epsilon设置为0.01
当学习编程时,while循环很棘手。在您强制中止它们之前,它们将使处理器处于忙碌状态。这也是导致文本编辑器崩溃的原因。high=ans而不是high-ans此代码肯定与编辑器崩溃无关。如果是的话,这将是离题的,属于superuser.com
while abs(ans**2 - x) >= epsilon: