斐波那契数列是一个数列,其中下一项是前两项的和。斐波那契数列的前两项是 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
循环是如何工作的
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 。打印 nextTerm。 |
1 | 1 | 2 | true 。打印 nextTerm。 |
1 | 2 | 3 | true 。打印 nextTerm。 |
... | ... | ... | ... |
34 | 55 | 89 | true 。打印 nextTerm。 |
55 | 89 | 144 | false 。终止循环。 |