为什么将乘号中的乘号更改为加号会产生这样的输出?

时间:2019-04-28 05:13:32

标签: python factorial

问题:为什么输出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

3 个答案:

答案 0 :(得分:0)

要获得期望的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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

(代表问题作者发布)

请教我一些解决问题的提示:1.了解循环的概念2.尝试自行打印答案-i = 5,n = 3,i = 8,n = 2,i = 10,n = 1,i = 11