简体   繁体   English

谁能帮助我在此python代码中找到Cube

[英]Can anyone help me in this python code for finding Cube

x=3
y=x
ans=0

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

There is no output on screen. 屏幕上没有输出。 And no error is showing up. 而且没有错误出现。 Just shown in image. 如图所示。

在此处输入图片说明

Your code only works for 3 cubed. 您的代码仅适用于3个立方体。 You're also using multiplication. 您还在使用乘法。 If you only want only addition as your comment implies, you'll probably want to break down your logic a bit. 如果您只希望添加注释所暗示的内容,则可能需要稍微分解一下逻辑。 Here's how I'd do it (stop reading here and try to work it out yourself, first!): 这是我的处理方式(请先停止在此处阅读,然后尝试自己尝试一下!):

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))

Outputs: 输出:

27
64
125

as expected. 如预期的那样。 Remember the easiest way to see output is to just save code to a file and run python from your command line. 请记住,查看输出的最简单方法是将代码保存到文件中,然后从命令行运行python

Your syntax is all off. 您的语法全部关闭。

You're using a capital X on the first line, then suddenly it's lowercase on the 2nd line. 您在第一行使用大写字母X,然后突然在第二行使用小写字母X。

while loops in python are generally written like this: python中的while循环通常是这样写的:

while y != 0 :

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM