问题:为什么输出11不是12? i + 4 + i + 3 + i + 2 = 1 + 4 + 1 + 3 + 1 + 2 = 12
码:
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
i = i * n --> i = i + n
n = n - 1
return i
print factorial(4)
11
要得到预期的i+4 + i+3 + i+2
和结果12
你需要
def factorial(n):
result = 0
i = 1
while n > 1:
result += i + n
n = n - 1
return result
print(factorial(4))
我添加到新的变量result
所以我不改变i
,它一直是1
。
我也使用>
而不是>=
所以它在i+2
之后结束并且它不添加i+1
def factorial(n):
i = 1
while n >= 1:
#I changed the signs from * to + after getting the factorial from * method.
print(i)
i = i + n
n = n - 1
return i
print(factorial(4))
如果你打印i,你会发现我在第一次循环后已经改变了。所以输出应该是1 + 4 + 3 + 2 + 1 = 11
(代表作者提问)。
我要解决问题的提示:1。理解循环的概念2.尝试自己打印答案 - i = 5,n = 3,i = 8,n = 2,i = 10,n = 1, I = 11