为什么我的阶乘在while循环中以零结束



这是我的代码:

inputNum = eval(input("enter number to calculate factorial"))
total = inputNum
j = 1
while j < total and inputNum != 0 :
j = j + 1
print("j is", j)
print("initial total is", total)
inputNum = inputNum-1
print("inputNum is", inputNum)
total = total * inputNum
print("total is", total)  
#once you get to j==5, it is greater than inputNum == 3
#I'm going to redefine while to be while j!=0
print("The factorial of", inputNum, "is", total)

现在,无论我输入什么数字,最后四行输出都会给我:

initial total is (inputNum!)
inputNum is 0
total is 0
The factorial of 0 is 0

我已经说过inputNum != 0了,那么一旦得到正确答案,为什么不停止呢?

在最后一次迭代中,inputNum0,然后将total乘以inputNum
例如,您可以先乘以total,然后减小inputNum

这是代码:

inputNum = eval(input("enter number to calculate factorial "))
total = 1
while inputNum > 0:
total = total * inputNum
inputNum = inputNum - 1
print(total)

结果:

enter number to calculate factorial 5
120

最新更新