C语言使用普通循环方法和递归求斐波那契序列示例代码
本文导语: 代码如下:#include int fac(int x); int main(void){ int n; scanf("%d", &n); if (n == 1 || n == 2) printf("1n"); else if (n == 3) printf("2n"); else { int last = 1; int sum = 2; for (int i...
#include
int fac(int x);
int main(void)
{
int n;
scanf("%d", &n);
if (n == 1 || n == 2)
printf("1n");
else if (n == 3)
printf("2n");
else
{
int last = 1;
int sum = 2;
for (int i = 3; i < n; ++i)
{
int temp = sum;
sum = sum + last;
last = temp;
}
printf("循环求出斐波那契序列值:%dn", sum);
}
int sum2 = fac(n);
printf("递归求出斐波那契序列值:%dn", sum2);
return 0;
}
//递归
int fac(int x)
{
static int f[50] = {1,1};
if (x == 1 || x == 2)
return f[x-1];
return f[x-1] == 0 ?
( f[x-1] = fac(x-1) + fac(x-2) ) :
f[x-1] ;
}