【问题标题】:Sublime2 keeps crashing? What is wrong with my python code?Sublime2 不断崩溃?我的 python 代码有什么问题?
【发布时间】:2014-10-26 19:22:03
【问题描述】:

我正在学习 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 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

有什么建议吗?

【问题讨论】:

  • high = ans 而不是 high-ans
  • 这段代码肯定与编辑器崩溃无关。如果是,这将是题外话,属于 superuser.com

标签: python macos sublimetext2


【解决方案1】:

应该是这样的:

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

答案如下所示:

low = 0.0 high = 12 ans = 6.0
low = 0.0 high = 6.0 ans = 3.0
low = 3.0 high = 6.0 ans = 4.5
low = 3.0 high = 4.5 ans = 3.75
low = 3.0 high = 3.75 ans = 3.375
low = 3.375 high = 3.75 ans = 3.5625
low = 3.375 high = 3.5625 ans = 3.46875
low = 3.375 high = 3.46875 ans = 3.421875
low = 3.421875 high = 3.46875 ans = 3.4453125
low = 3.4453125 high = 3.46875 ans = 3.45703125
numGuesses = 10
3.462890625 is close to square root of 12

【讨论】:

    【解决方案2】:

    你在一个无穷无尽的while-循环中。当您查看此部分时:

    while abs(ans**2 - x) >= epsilon:
    

    while abs(ans**2 - x) 总是给出 24,而epsilon 设置为 0.01。

    在学习编程时,while 循环很棘手。它们将使您的处理器保持忙碌,直到您强行中止它们。这也是导致您的文本编辑器崩溃的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      相关资源
      最近更新 更多