發布時間:2021-03-24 19:56 作者:獨孤劍 閱讀:2175
#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,
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞