Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么从阶乘的乘法符号到加法符号的变化会产生这样的结果?_Python_Factorial - Fatal编程技术网

Python 为什么从阶乘的乘法符号到加法符号的变化会产生这样的结果?

Python 为什么从阶乘的乘法符号到加法符号的变化会产生这样的结果?,python,factorial,Python,Factorial,问题:为什么输出11不是12? i+4+i+3+i+2=1+4+1+3+1+2=12 代码: 要获得预期的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

问题:为什么输出11不是12? i+4+i+3+i+2=1+4+1+3+1+2=12

代码:


要获得预期的
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,您将发现在第一次循环后i已更改。 因此,输出应该是1+4+3+2+1=11(代表问题作者发布)


解决问题的建议:1。理解循环2的概念。试着自己打印答案-i=5,n=3,i=8,n=2,i=10,n=1,i=11

您正在将4,3,2,1添加到1中,这是11使用
print(i,n)
inside
查看变量中的值,它可以帮助您找到问题。因为
1+4+3+2+1=11
==>第一个循环:
1+4
第二个循环:
5+3
第三个循环:
8+2
。。。
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))