2025年3月13日 星期四 甲辰(龙)年 月十二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言计算斐波那契数列

时间:01-03来源:作者:点击数:32

打印 N 的斐波那契数列,代码如下:

  • #include <stdio.h>
  • int main(void) {
  • int n; // 输入一个数字 N
  • int i; // 第 i 个将要输出的斐波那契数
  • int current; // 第 i 个斐波那契数的值
  • int next; // 下一个(i+1)斐波那契数的值
  • int twoaway; // 下下个(i+2)斐波那契数的值
  • printf("How many Fibonacci numbers do you want to compute? ");
  • scanf("%d", &n);
  • if (n<=0)
  • printf("The number should be positive.\n");
  • else {
  • printf("\n\n\tI \t Fibonacci(I) \n\t=====================\n");
  • next = current = 1;
  • for (i=1; i<=n; i++) {
  • printf("\t%d \t %d\n", i, current);
  • twoaway = current+next;
  • current = next;
  • next = twoaway;
  • }
  • }
  • }

可能的输出结果:

How many Fibonacci numbers do you want to compute? 9

I   Fibonacci(I)
=====================
1     1
2     1
3     2
4     3
5     5
6     8
7     13
8     21
9     34

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门