您的位置:首页 > 其它

递归和非递归分别实现求第n个斐波那契数

2019-05-12 21:16 197 查看

递归和非递归分别实现求第n个斐波那契数
递归:

#include<stdio.h>
#include<Windows.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int res = fib(5);
printf("%d\n", res);
system("pause");
return 0;
}

非递归:

#include<stdio.h>
#include<Windows.h>
int fib2(int n)
{
int first = 1;
int scend = 1;
int third = 1;
while (n>2){
third = first + scend;
first = scend;
scend = third;
n--;
}
return third;
}
int main()
{
int res = fib2(4200);
printf("%d\n", res);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: