python - 任何人都可以在这个 python 代码中帮助我找到 Cube
问题描述
x=3
y=x
ans=0
while( y != 0 ):
ans = ans + x
y = y - 1
ans = ans*x
print( str(ans) )
屏幕上没有输出。并且没有出现错误。如图所示。
解决方案
您的代码仅适用于 3 立方。你也在使用乘法。如果您只想添加评论所暗示的内容,那么您可能需要稍微分解一下您的逻辑。这是我的做法(停止阅读这里并尝试自己解决,首先!):
def cube(x):
""" Calculate x to the 3rd power (cube) """
x_times_x = multiply(x, x)
x2_times_x = multiply(x_times_x, x)
return x2_times_x
def multiply(x, y):
""" Multiplies two numbers only using addition """
accum = 0
for _ in range(y):
accum += x
return accum
print(cube(3))
print(cube(4))
print(cube(5))
输出:
27
64
125
正如预期的那样。请记住,查看输出的最简单方法是将代码保存到文件并从命令行运行python
。
推荐阅读
- sql - 错误->有人可以(向新手)解释如何在选择语句中加入子查询之外吗?
- asp.net-core - 在 .NET Core 项目中使用 PackageReference 引用时,nuget 包的默认版本是什么?
- node.js - NodeJS WebSockets (ws) 模块是否实现背压?
- angular - 如何使用 Angular 向 API Gateway 发出 Get 请求?
- osquery - osquery - 使用 osqueryi 和禁用日志记录时的警告
- python - 减少冗余编码 Python 3
- python - 字典 get() 方法的 Python 3X 评估行为
- pandas - 在我的代码中获取'对象不可迭代错误
- laravel - Eloquent 使用 ->where() 返回不可预测的结果
- python-3.x - Python - 将字符转换为位串