用於計算第 n 個斐波那契數的 C/C++ 程式?


Fibonacci 序列是一個數列,其中後一項是前兩項之和。Fibonacci 序列的前兩項是 0 後面跟著 1。

在這個題目中,我們將找出 Fibonacci 數列中的第 n 個數。為此,我們將計算所有數字並打印出第 n 項。

Input:8
Output:0 1 1 2 3 5 8 13

說明

0+1=1
1+1=2
1+2=3
2+3=5

利用 For 迴圈求前兩項之和得到後一項

示例

#include<iostream>
using namespace std;
int main() {
   int t1=0,t2=1,n,i,nextTerm;
   n = 8;
   for ( i = 1; i <= n; ++i) {
      if(i == 1) {
         cout << " " << t1 ;
         continue;
      }
      if(i == 2) {
         cout << " " << t2 << " " ;
         continue;
      }
      nextTerm = t1 + t2 ;
      t1 = t2 ;
      t2 = nextTerm ;
      cout << nextTerm << " ";
   }
}

輸出

0 1 1 2 3 5 8 13

更新時間:2019-08-19

697 次瀏覽

開啟您的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.