【问题标题】:Loop that won't stop?不会停止的循环?
【发布时间】:2014-02-06 04:22:18
【问题描述】:

我是 Python 新手,我正在尝试编写一个循环来找到最大的整数 n,因此 n^3

这是我的代码:

working = True

n = 12000

while working:
    n = n - 1
    if ((n * n * n) < 12000) and not working:
        print(n)

【问题讨论】:

  • while True: print("tears")
  • 您可以使用电源运算符并使用n ** 3 而不是n * n * n

标签: python loops while-loop integer


【解决方案1】:

这段代码中没有任何内容将working 的值设置为False,因此working 始终为True,因此循环永远不会退出。

【讨论】:

  • 对。 not working 的计算结果为 working 的否定,但不会改变该变量的值。
  • @user3105664 to assign to working 你必须说working = X。 Python 与 C 的不同之处在于不能在条件中执行赋值。总的来说,这是一件好事。
  • @NickT 要在 C 中执行分配,您通常仍然必须使用 = 尽管 ;-)
【解决方案2】:

找到答案后,需要将working标志转为False,像这样

while working:
    n = n - 1
    if ((n * n * n) < 12000):   # You don't need the  `and not working:` check
        print(n)
        working = False

顺便说一句,在 Python 中,您可以像这样找到数字的幂

n ** 3 == n * n * n

事实证明,您的实际问题的答案是22 :)

【讨论】:

【解决方案3】:

线

while working:

表示只要workingTrue,您就会继续循环。您永远不会在循环内将working 设置为False,因此它将永远循环。

你可能想要这样的东西:

while working:
    n = n - 1
    if ((n * n * n) < 12000):
        working = False
        print(n)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多