斐波那契数列是一个序列,其中下一项是前两项之和。斐波那契数列的前两项是 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 项之前,我们已经打印了斐波那契数列的前两项。
让我们看看
<表> 我 t1 t2 下一个学期 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
for
循环是如何工作的:
到一定数量的斐波那契数列
#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 。终止循环。 |