为什么乘法符号中的乘法符号的变化会给出这样的输出?

问题描述 投票:-2回答:3

问题:为什么输出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
python factorial
3个回答
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


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


0
投票

(代表作者提问)。

我要解决问题的提示:1。理解循环的概念2.尝试自己打印答案 - i = 5,n = 3,i = 8,n = 2,i = 10,n = 1, I = 11

© www.soinside.com 2019 - 2024. All rights reserved.