解题思路:递归的全名叫做递推和归回,它是不断的递推和归回
斐波那契数列又名叫兔子数列,f(0)=1;f(1)=1;f(2)=2......从这我们可以得出一个表格
1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
注意事项:如果递归使用的不恰当会造成不必要的麻烦,而假设n的数较大,容量值则会不断上,会导致一些问题出现,而且此题如果实在想不出递归关系可以使用迭代方法,动态分配,尾递归来求解。
参考代码:
1.递归方法
#include<stdio.h> int Fib(int n) //运用递归方法解决斐波那契数列问题 { if(n<=2) return 1; else return Fib(n-1)+Fib(n-2); //这个是指当n>2时候的结果 } int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) { printf("%d ",Fib(i)); } return 0; }
2.迭代方法(此方法借用“教你夺冠”这位博主的方法)
#include <stdio.h>
#include <string.h>
long
fibonacci(
int
n)
{
if
(n <= 2)
{
return
1;
}
long
result;
long
pre_result;
long
pre_pre_result;
pre_result = pre_pre_result = 1;
while
(n > 2)
{
result = pre_result + pre_pre_result;
pre_pre_result = pre_result;
pre_result = result;
n--;
}
return
result;
}
int
main()
{
int
N;
scanf
(
"%d"
, &N);
int
i;
0.0分
0 人评分
字符串的输入输出处理 (C语言代码)浏览:2122 |
采药 (C++代码)浏览:1265 |
2006年春浙江省计算机等级考试二级C 编程题(2) (C++代码)直接打表啊8以上值不变hhh浏览:637 |
点我有惊喜!你懂得!浏览:2071 |
C语言训练-阶乘和数* (C语言代码)浏览:981 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:732 |
C语言训练-自由落体问题 (C语言代码)浏览:1733 |
分糖果 (C++代码)浏览:1438 |
简单的a+b (C++语言代码)浏览:853 |
拆分位数 (C语言代码)浏览:1326 |