递归和非递归分别实现求第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;
}
1981

被折叠的 条评论
为什么被折叠?



