C說話應用通俗輪回辦法和遞歸求斐波那契序列示例代碼。本站提示廣大學習愛好者:(C說話應用通俗輪回辦法和遞歸求斐波那契序列示例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是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] ;
}