python - 不理解 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
我想知道是否有人可以帮助我意识到我做错了什么。
解决方案
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
推荐阅读
- java - (辅助功能)使用 TalkBack 时将自动焦点更改为其他组件
- c# - 如何从 asp.net 应用程序获取所有活动会话
- node.js - 使用 ExcelJS 将多个工作表添加到流工作簿
- windows - Input.GetAxis("Mouse X") 不适用于某些 Windows 配置
- laravel - 将 where 子句保存在变量中并在 laravel 查询中使用
- ios - Metal中的纹理数组
- c# - 如何通过 C# 将 js-object 转换为 json?
- javascript - 是否可以发送内容类型为 multipart/form-data(文件)的 Http post 请求和带有数据参数的 json 对象?
- excel - VBA:内容删除替换
- vb.net - 想要使用 VB.net 中的按钮将文件从一个位置传输到另一个位置