C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 显示斐波那契数列的程序

显示斐波那契数列的 C 程序

在本例中,您将学习显示前 n 个数字(由用户输入)的斐波那契数列。
要理解此示例,您应该了解以下C 编程 主题:
C 编程运算符 C while 和 do...while 循环 C for 循环 C 中断并继续
斐波那契数列是一个序列,其中下一项是前两项之和。斐波那契数列的前两项是 0 后跟 1、
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
访问此页面以了解斐波那契数列。

最多 n 项的斐波那契数列

#include <stdio.h>
int main() {
  int i, n;
  // initialize first and second terms
  int t1 = 0, t2 = 1;
  // initialize the next term (3rd term)
  int nextTerm = t1 + t2;
  // get no. of terms from user
  printf("Enter the number of terms: ");
  scanf("%d", &n);
  // print the first two terms t1 and t2
  printf("Fibonacci Series: %d, %d, ", t1, t2);
  // print 3rd to nth terms
  for (i = 3; i <= n; ++i) {
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }
  return 0;
}
输出
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 
让我们假设 n = 10。首先,在使用 for 循环打印接下来的 n 项之前,我们已经打印了斐波那契数列的前两项。
让我们看看 for 循环是如何工作的:
<表> 我 t1 t2 下一个学期 3 0 1 1 4 1 1 2 5 1 2 3 6 2 3 5 7 3 5 8 8 5 8 13 9 8 13 21 10 13 21 34

到一定数量的斐波那契数列

#include <stdio.h>
int main() {
  int t1 = 0, t2 = 1, nextTerm = 0, n;
  printf("Enter a positive number: ");
  scanf("%d", &n);
  // displays the first two terms which is always 0 and 1
  printf("Fibonacci Series: %d, %d, ", t1, t2);
  nextTerm = t1 + t2;
  while (nextTerm <= n) {
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }
  return 0;
}
输出
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 
在这个程序中,我们使用了一个 while 循环来打印直到 n 的所有斐波那契数列。
如果 n 不是斐波那契数列的一部分,我们将序列打印到最接近(且小于) n 的数字。
假设 n = 100。首先,我们打印前两项 t1 = 0t2 = 1
然后 while 循环使用 nextTerm 变量打印序列的其余部分:
t1 t2 nextTerm nextTerm <= n
0 1 1 true。打印 nextTerm.
1 1 2 true。打印 nextTerm.
1 2 3 true。打印 nextTerm.
... ... ... ...
34 55 89 true。打印 nextTerm.
55 89 144 false。终止循环。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4