第一种(从零开始)
def fib():
num = input('')
i,a,b = 0,0,1
if int(num) < 0:
print('重新输入')
elif int(num) == 1:
print(a)
else:
while i < int(num):
print(a)
#sum = a + b
#a = b
#b = sum
a,b = b,a + b
i += 1
fib()
第二种(从零开始)
def fib(num):
fibs = [0,1]
for i in range(num - 2):
fibs.append(fibs[-2] + fibs[-1])
print(fibs)
fib(13)
第三种(从一开始)
def fib(max):
a,n,b = 0,0,1
list = []
while n < max:
list.append(b)
a,b = b,a + b
n += 1
print(list)
return list
fib(13)
第四种(从一开始)
def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a + b
print(a)
fib(13)
第五种(从一开始)
def fib(n):
a = 0
b = 1
i = 0
while i < n:
print(b)
a,b = b,a + b
i = i + 1
fib(13)
第六项(从0开始)(不建议使用)(后面多逗号)
nterms = int(input("你需要几项?"))
n1 = 0
n2 = 1
count = 2
if nterms <= 0:
print("请输入一个正整数。")
elif nterms == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列:")
print(n1,",",n2,end=" , ")
while count < nterms:
nth = n1 + n2
print(nth,end=" , ")
n1 = n2
n2 = nth
count += 1