使用迭代查詢斐波那契數的 C++ 程式


以下是一個透過迭代查詢斐波那契數的示例。

示例

 線上演示

#include <iostream>
using namespace std;
void fib(int num) {
   int x = 0, y = 1, z = 0;
   for (int i = 0; i < num; i++) {
      cout << x << " ";
      z = x + y;
      x = y;
      y = z;
   }
}
int main() {
   int num;
   cout << "Enter the number : ";
   cin >> num;
   cout << "\nThe fibonacci series : " ;
   fib(num);
   return 0;
}

輸出

Enter the number : 10
The fibonacci series : 0 1 1 2 3 5 8 13 21 34

在上面的程式中,實際程式碼存在於函式 fib() 中,用於計算斐波那契數列。

void fib(int num) {
   int x = 0, y = 1, z = 0;
   for (int i = 0; i < num; i++) {
      cout << x << " ";
      z = x + y;
      x = y;
      y = z;
   }
}

在 main() 函式中,使用者輸入一個數字。呼叫函式 fib(),如下一行所示列印斐波那契數列 −

cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num);

更新於: 2020 年 6 月 26 日

7K+ 瀏覽次數

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.