#include<stdio.h>
#include<Windows.h>
int fib1(const int n)//非递归
{
int a = 1;
int b = 1;
int sum = 0;
int i = 0;
for (i = 3; i <= n; i++)
{
sum = a + b;
a = b;
b = sum;
}
return sum;
}
int fib2(const int n)//递归
{
if (n <= 2)
{
return 1;
}
else
{
return fib2(n - 1) + fib2(n - 2);
}
}
int main()
{
int n = 20;
printf("fib1 = %d\n", fib1(n));
printf("fib2 = %d\n", fib2(n));
system("pause");
return 0;
}
用递归和非递归分别实现求第n个斐波那契数。
最新推荐文章于 2021-12-07 15:08:51 发布