首页 > 解决方案 > 不理解 for 循环

问题描述

我需要使用 for 循环找到完美立方体的立方根,但我不知道为什么我的代码不起作用:

n = int(input('n = '))
for guess in range(0, n+1):
    if guess**3 != n:
        guess = guess + 1
    if guess**3 == n:
        print(guess, 'is the cube root of', n)
    if guess**3 != n:
        print("not a perfect cube")

如果我输入数字 8(例如),它将打印出:

n = 8
not a perfect cube
2 is the cube root of 8
2 is the cube root of 8
not a perfect cube
not a perfect cube
not a perfect cube
not a perfect cube
not a perfect cube
not a perfect cube

我想知道是否有人可以帮助我意识到我做错了什么。

标签: pythonpython-3.xloopscube

解决方案


n**(1/3) 也会给你 n 的立方根。

您的代码可以通过以下方式改进:

    n = int(input('n = '))
    for guess in range(0, n+1):
        if guess**3 == n:
            print(guess, 'is the cube root of', n)
            break
    else:
        print("not a perfect cube")

你不需要guess=guess+1


推荐阅读