打印 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