生成斐波那契数列的 C 程序
在本例中,您将学习使用 C 语言生成的斐波那契数列前 n (由用户输入)个数字。
要理解此示例,您应该具备以下 C 语言编程主题的知识:
斐波那契数列是一个序列,其中下一项是前两项之和。斐波那契数列由是 0 和 1 开始。
斐波那契数列: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
循环打印下一项之前已经打印了斐波那契数列的前两项。
让我们看看 for
循环是如何工作的:
i |
t1 |
t2 |
nextTerm |
---|---|---|---|
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 = 0
和 t2 = 1
。
然后 while
循环使用变量 nextTerm
打印剩下的序列:
t1 |
t2 |
nextTerm |
nextTerm <= n |
---|---|---|---|
0 | 1 | 1 | true |
1 | 1 | 2 | true |
1 | 2 | 3 | true |
… | … | … | … |
34 | 55 | 89 | true |
55 | 89 | 144 | false |