要輸出斐波那契數(shù)列,可以使用迭代或遞歸的方法來實(shí)現(xiàn)。以下是兩種實(shí)現(xiàn)方式:
def fibonacci(n):
# 初始的斐波那契數(shù)列的前兩個(gè)數(shù)
a, b = 0, 1
# 循環(huán)計(jì)算斐波那契數(shù)列
for _ in range(n):
print(a)
a, b = b, a + b
# 輸入要輸出斐波那契數(shù)列的個(gè)數(shù)
n = int(input("請輸入要輸出斐波那契數(shù)列的個(gè)數(shù):"))
fibonacci(n)
def fibonacci(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib = fibonacci(n - 1)
fib.append(fib[-1] + fib[-2])
return fib
# 輸入要輸出斐波那契數(shù)列的個(gè)數(shù)
n = int(input("請輸入要輸出斐波那契數(shù)列的個(gè)數(shù):"))
fib = fibonacci(n)
for num in fib:
print(num)
無論使用迭代還是遞歸方式,都能輸出前n個(gè)斐波那契數(shù)列的數(shù)。