斐波那契 问第n个斐波那契数是多少?循环实现:
a = 1 b = 1 while 1: n = int(input('请输入你要计算第几个斐波那契数:')) for i in range(1,n+1): if i == 1 or i == 2: a = 1 b = 1 else: a,b=a+b,a print(a)
递归实现:
def fib(n): if n == 1 or n == 2: return 1 return fib(n-1) + fib(n-2) print(fib(4))
def fib(n,l=[0]): l[0] +=1 if n == 1 or n == 2: l[0] -=1 return 1,1 else: a,b = fib(n - 1) l[0] -= 1 if l[0] == 0: return a+b return b,a+b print(fib(6))