为什么此查找阶乘的代码仅适用于单个输入?

时间:2018-10-19 07:31:53

标签: python python-2.7 math

对于多个输入,这显示了奇怪的结果,例如:对于 2、4、5 ,它的输出显示为 24、24

T = int(raw_input())
L = [] 
for i in range(0,T):
num = int(raw_input())
L.append(num)
product = 1
k = 0
for item in L:
    while k < item:
        term = item - k
        product = product * term
        k = k + 1
    print product   

1 个答案:

答案 0 :(得分:1)

您应该修复第一个for循环的缩进。然后在主product循环内初始化kfor,以便可以为每个输入数字重置它们。变量term是多余的,因为您可以简单地将product乘以k

T = int(raw_input())
L = [] 
for i in range(0,T):
    num = int(raw_input())
    L.append(num)
for item in L:
    k = 1
    product = 1
    while k <= item:
        product = product * k
        k = k + 1
    print product