C 語言實例 - 斐波那契數列
斐波那契數列指的是這樣一個數列 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項開始,每一項都等於前兩項之和。
實例 - 輸出指定數量的斐波那契數列
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
printf("輸出幾項: ");
scanf("%d", &n);
printf("斐波那契數列: ");
for (i = 1; i <= n; ++i)
{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
運行結果:
輸出幾項: 10 斐波那契數列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
實例 - 輸出指定數字前的斐波那契數列
#include <stdio.h>
int main()
{
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("輸入一個正數: ");
scanf("%d", &n);
// 顯示前兩項
printf("斐波那契數列: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while(nextTerm <= n)
{
printf("%d, ",nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
運行結果:
輸入一個正數: 100 斐波那契數列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,