簡體   English   中英

為什么我的階乘在我的 while 循環中以零結尾?

[英]Why does my factorial end in zero in my while loop?

這是我的代碼:

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)

現在,無論我輸入什么數字,output 的最后四行都會給我:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM