在grok学习上学习python,并在这个问题上有点为难。我需要一个程序来产生这个输出:
Enter a negative number: -6
720公式是:-1 x -2 x -3 x -4 x -5 x -6 = -720
我的代码:
n = int(input('Enter a negative number: '))
result = 0
for i in range(-1*n):
result = result + i
print(result)发布于 2017-10-12 08:21:45
如果为n = 6,则range(-1 * n)将为0, 1, 2, 3, 4, 5。这些不是你想要的数字,你想要的是-6, -5, -4, -3, -2, -1。要获得该序列,您应该使用range(n, 0)。
你应该做乘法,而不是加法。这也意味着您需要使用1而不是0来初始化结果,因为乘以0总是0。
n = int(input('Enter a negative number: '))
result = 1
for i in range(n, 0):
result *= i
print(result)https://stackoverflow.com/questions/46699420
复制相似问题