leizhenzi23 发表于 2021-8-18 10:18:45

斐波那契数列,迭代实现时候,为什么while 里 n-= 1呢

1 def fab(n):
2   n1 = 1
3   n2 = 1
4   n3 = 1
5   
6   if n < 1:
7         print("输入有误!")
8         return -1
9   while (n-2)>0:
10         n3 = n2 + n1
11         n1 = n2
12         n2 = n3
13         n -= 1
14   return n3
15
16 num = int(input("请输入天数:"))
17 result = fab(num)
18 if result != -1:
19   print("总共有%d对小兔崽子诞生!" % result)

青出于蓝 发表于 2021-8-18 10:22:44

n在这里是一个计数变量,代表月数。
n到0的时候,n月就过去了,则while循环停止
如果n不等于0,则还会有小兔子,while循环继续,每循环一次,月数减1。
所以while循环里有n-=1
欢迎追问

leizhenzi23 发表于 2021-8-18 10:41:42

问下:循环体里的n 和 while 条件 n-2的 n 代表的是一个意义么。大佬
页: [1]
查看完整版本: 斐波那契数列,迭代实现时候,为什么while 里 n-= 1呢