迭代实现如下:

def fab(n):
n1 = 1
n2 = 1
if n<1:
print("输入有误!")
return -1
while (n-2)>0:
n3 = n2+n1
n1 = n2
n2 = n3
n-=1
return n3
number = int(input("请输入要求的斐波那契数的第几个数:"))
result = fab(number)
print(result)

递归实现如下:

def fab(n):
if n==1 or n==2:
f = 1
else:
f = fab(n-1)+fab(n-2)
return f
number = int(input("请输入要求的斐波那契数的第几个数:"))
result = fab(number)
print(result)
05-11 13:17