C语言使用普通循环方法和递归求斐波那契序列示例代码

时间:2021-11-01 07:57:14

复制代码 代码如下:


#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] ;
}