我目前在Python編碼類,這是一個任務。我的代碼中顯然有一個無限循環,但我似乎無法找到它。被告知我有一個無限循環,但我不確定如何解決它。 (Python編碼課程)
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
# At this point the program should take your now factorial and give you the fibonacci sequence
# takes your factorial and makes it the fibonacci
nterms = factorial
# first two terms
n1 = 0
n2 = 1
count = 2
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=', ')
while count < nterms:
nth = n1 + n2
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1
我用兩個調試工具,試圖通過運行程序,並嘗試各種突破序列找到自己的問題,但我只是沒有抓住它。
你沒有無限循環,當我輸入12個nterms是'479001600'讓您擁有一個慢長的環路,不是無限的。第n個變得非常大,所以計算和打印它也增加了開銷。 –
你是什麼意思「我顯然在我的代碼中有一個無限循環」?誰,或者什麼,告訴你,你有一個無限循環? –
我的老師告訴我我的代碼中有一個無限循環,這使我無法接受信用。 – Packy502