斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368…这个数列从第3项开始,每一项都等于前两项之和。
要求:从控制台获取斐波那契数列的数量,输出指定数列。
实现方法1:使用 for循环,将t1赋值第1个数,t2赋值第2个数,计算出第3个数,输出第1个数。然后再将t1赋值第2个数,t2赋值第3个数,计算出第4个数,输出第2个数。以此类推。
代码:
#include <stdio.h>
int main()
{
int i, n, t1 =1, t2 = 1, nextTerm;
printf("输出多少项: ");
scanf_s("%d", &n);
printf("斐波那契数列%d项: ",n);
for (i = 1; i <= n; ++i)
{
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
实现方法2:使用while循环,将t1赋值第1个数,t2赋值第2个数,先输出前两项t1,t2。计算出第3个数,判断第3项是否为输出项,若满足输出该项,将t1赋值第2个数,t2赋值第3个数,计算出第4个数,以此类推。
代码:
#include <stdio.h>
int main()
{
int t1 = 1, t2 = 1, nextTerm = 0, n;
printf("输出多少项: ");
scanf_s("%d", &n);
// 显示前两项
printf("斐波那契数列%d项: %d %d ", n, t1, t2);
nextTerm = t1 + t2;
int i = 3;
while (i <= n)
{
printf("%d ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
i++;
}
return 0;
}