21xrx.com
2024-04-25 07:29:23 Thursday
登录
文章检索 我的文章 写文章
C 中的斐波那契数列
2021-07-06 22:24:21 深夜i     --     --
C

C 中使用循环和递归的斐波那契数列。 您可以根据需要打印尽可能多的系列术语。 序列的数字被称为斐波那契数。

数列的前几项是0, 1, 1, 2, 3, 5, 8, ...,除了数列的前两项外,每隔一项都是前两项之和,例如8 = 3 + 5(3 和 5 之和)。

 

C 中的斐波那契数列程序

#include <stdio.h>


int main()
{
  int n, first = 0, second = 1, next, c;

  printf("Enter the number of terms\n");
  scanf("%d", &n);

  printf("First %d terms of Fibonacci series are:\n", n);

  for (c = 0; c < n; c++)
  {
    if (c <= 1)
      next = c;
    else
    {
      next = first + second;
      first = second;
      second = next;
    }
    printf("%d\n", next);
  }

  return 0;
}

 

程序输出:

使用递归的斐波那契数列 C 程序

#include<stdio.h>


int f(int);

int main()
{
  int n, i = 0, c;

  scanf("%d", &n);

  printf("Fibonacci series terms are:\n");

  for (c = 1; c <= n; c++)
  {
    printf("%d\n", f(i));
    i++;
  }

  return 0;
}

int f(int n)
{
  if (n == 0 || n == 1)
    return n;
  else
    return (f(n-1) + f(n-2));
}

递归方法效率较低,因为它涉及重复的函数调用,在计算系列的较大项时可能会导致堆栈溢出。

使用 Memoization(将计算的斐波那契数存储在数组中并将其用于查找),我们可以减少递归算法的运行时间。 该系列在数学和计算机科学中有许多应用。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章