C语言使用普通循环方法和递归求斐波那契序列示例代码
#include <stdio.h>
int fac(int x);
int main(void)
{
int n;
scanf("%d", &n);
if (n == 1 || n == 2)
printf("1\n");
else if (n == 3)
printf("2\n");
else
{
int last = 1;
int sum = 2;
for (int i = 3; i < n; ++i)
{
int temp = sum;
sum = sum + last;
last = temp;
}
printf("循环求出斐波那契序列值:%d\n", sum);
}
int sum2 = fac(n);
printf("递归求出斐波那契序列值:%d\n", 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] ;
}
栏 目:C代码
下一篇:C语言中access/_access函数的使用实例详解
本文标题:C语言使用普通循环方法和递归求斐波那契序列示例代码
本文地址:http://www.codeinn.net/misctech/73064.html