斐波那契数列是一个整数序列 0, 1, 1, 2, 3, 5, 8...
前两项是 0 和 1。所有其他项都是通过将前面两项相加得到的。这意味着第 n 项是 (n-1) 项和 (n-2) 项的和。
源代码
代码可视化:想看看斐波那契数列是如何构建的吗?试试我们的逐行代码可视化工具。
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
输出
How many terms? 7 Fibonacci sequence: 0 1 1 2 3 5 8
在这里,我们将项数存储在 nterms 中。我们将第一项初始化为 0,第二项初始化为 1。
如果项数大于 2,我们使用 while
循环通过将前两项相加来找到序列中的下一项。然后我们交换变量(更新它)并继续这个过程。
你也可以使用递归打印斐波那契数列。