首页 > 解决方案 > 任何人都可以在这个 python 代码中帮助我找到 Cube

问题描述

x=3
y=x
ans=0

while( y != 0 ):
  ans = ans + x
  y = y - 1
ans = ans*x
print( str(ans) )

屏幕上没有输出。并且没有出现错误。如图所示。

在此处输入图像描述

标签: python

解决方案


您的代码仅适用于 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


推荐阅读