我在這里看到的許多問題和答案都給出了多個輸出的答案,但是我只想要一個答案,有人可以幫忙嗎?例如,使用此代碼,當您在這種情況下選擇一個數字 '9' 時,您會得到 '0, 1, 1, 2, 3, 5, 8, 13, 21' 我想要的是如果我說 '9' 我只是得到'21' 在它之前什么都沒有。
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 n2
n1 = n2
n2 = nth
count = 1
uj5u.com熱心網友回復:
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
if count 1 >= nterms:
print(n1)
nth = n1 n2
n1 = n2
n2 = nth
count = 1
uj5u.com熱心網友回復:
嘗試這個:
nterms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < (nterms-1):
nth = n1 n2
n1 = n2
n2 = nth
count = 1
print(n1)
uj5u.com熱心網友回復:
您可以創建一個長度為“nterms”的串列,并使用 array.pop 獲取它的最后一個元素。或者您可以將 fibonaci 的當前值分配給變數,并在回圈完成時列印最后分配的值。
def fibo():
while count < nterms:
f = a b
a = b
b = f
count = 1
print(f)
uj5u.com熱心網友回復:
您可以使用函式遞回計算n序列的數量:
def fibMem(n, mem={}):
if n in mem:
return mem[n]
if n <= 1:
return 1
mem[n] = fibMem(n-1, mem) fibMem(n-2, mem)
return mem[n]
num = 9
print(fibMem(num-2))
uj5u.com熱心網友回復:
根據您的原始代碼,我建議只制作一個僅列印最終數字的函式:
def final_fib(nterms, print_all=False):
n1, n2, count = 0, 1, 0
if nterms <= 0:
print("Please enter a positive integer")
return
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
return(n1)
fib_nrs = list()
fib_nrs.append(n1)
while count < nterms:
if print_all:
print(n1)
fib_nrs.append(n1)
nth = n1 n2
n1 = n2
n2 = nth
count = 1
if not print_all:
print(fib_nrs[-1])
這會給:
final_fib(9)
21
請注意,我還通過設定print_all=False. 那是;
final_fib(9, print_all=True)
0
1
1
2
3
5
8
13
21
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/345162.html
上一篇:如何在此類中添加original_text和reversed_text屬性?我應該如何修復它以獲得理想的輸出?
下一篇:方法外的類內代碼vs類外的代碼
