递归实现求第n个斐波那契数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int fib(int n)
{
if (n <= 2)
return 1;
else
return fib(n - 1) + fib(n - 2);
}
int main()
{
int n, ret;
scanf("%d", &n);
ret = fib(n);
printf("%d\n", ret);
system(“pause”);
return 0;
}
非递归求斐波那契数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int fib(int n)
{
int a = 1;
int b = 1;
int result = 0;
if (n <= 2)
return 1;
else
{
for (int i = 3; i <= n; ++i)
{
result = a + b;
a = b;
b = result;
}
return result;
}
}
int main()
{
int n, ret;
scanf("%d", &n);
ret = fib(n);
printf("%d\n", ret);
system(“pause”);
return 0;
}
递归和非递归求斐波那契数
最新推荐文章于 2023-12-09 23:00:38 发布