x=3
y=x
ans=0
while( y != 0 ):
ans = ans + x
y = y - 1
ans = ans*x
print( str(ans) )
屏幕上没有输出。并且没有显示任何错误。如图所示。
发布于 2018-08-04 03:20:20
你的代码只适用于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
。
发布于 2018-08-04 02:56:58
你的语法都是错误的。
你在第一行使用大写的X,然后在第二行突然变成了小写。
python中的while
循环通常是这样编写的:
while y != 0 :
https://stackoverflow.com/questions/51678572
复制相似问题