鍍金池/ 教程/ C++/ C++斐波納契數(shù)列
C++用戶定義異常
C++ this指針
C++存儲類
C++函數(shù)
C++交換變量值
C++ continue語句
C++注釋
C++函數(shù)遞歸
C++ goto語句
C++函數(shù)-通過值調(diào)用和引用調(diào)用
C++重載
C++語言歷史
C++反轉數(shù)字
C++ try/catch語句
C++是什么?
C++變量
C++ break語句
C++運算符
C++第一個程序
C++繼承
C++虛函數(shù)
C++將十進制轉換為二進制
C++矩陣乘法
C++對象和類
C++基礎輸入輸出(cin,cout,endl)
C++文件和流
C++求素數(shù)
C++ if/else語句
C++友元函數(shù)
C++命名空間
C++面向?qū)ο蟾拍?/span>
C++階乘
C++關鍵字
C++重載
C++聚合
C++結構體
C++的特點(特性)
C++打印字母表三角
C++ switch語句
C++多態(tài)
C++ do-while循環(huán)
C++字符串
C++ static關鍵字
C++錯誤處理
C++ for循環(huán)
C語言與C++的區(qū)別
C++ while循環(huán)
C++開發(fā)環(huán)境的安裝
linux環(huán)境下編譯C++ 程序
C++枚舉
C++指針
C++斐波納契數(shù)列
C++阿姆斯壯數(shù)字
C++接口
C++教程
C++數(shù)組
C++數(shù)據(jù)抽象
C++回文程序?qū)嵗?/span>
C++打印數(shù)字三角
C++將數(shù)組傳遞到函數(shù)
C++多維數(shù)組
C++將數(shù)字轉換字符

C++斐波納契數(shù)列

C++中的斐波納契系數(shù)實現(xiàn):在斐波納契系列的情況下,下一個數(shù)字是前兩個數(shù)字的總和,例如:0,1,1,2,3,5,8,13,21等。斐波那契數(shù)列的前兩個數(shù)字是:01。

有兩種方法來寫斐波那契數(shù)列程序:

  • 不使用遞歸實現(xiàn)斐波那契數(shù)列
  • 使用遞歸實現(xiàn)斐波那契數(shù)列

不使用遞歸實現(xiàn)斐波那契數(shù)列

下面來看看看不使用遞歸在C++中實現(xiàn)斐波那契數(shù)列(fibonacci)程序。

#include <iostream>  
using namespace std;  
int main() {  
    int n1=0,n2=1,n3,i,number;    
    cout<<"Enter the number of elements: ";    
    cin>>number;    
    cout<<n1<<" "<<n2<<" "; //printing 0 and 1  
    //loop starts from 2 because 0 and 1 are already printed    
    for(i=2;i<number;++i) 
    {    
        n3=n1+n2;    
        cout<<n3<<" ";    
        n1=n2;    
        n2=n3;    
    }    
    return 0;  
}

執(zhí)行上面代碼,得到以下結果 -

Enter the number of elements: 10
0 1 1 2 3 5 8 13 21 34

在C++中使用遞歸實現(xiàn)斐波那契數(shù)列

下面來看看看使用遞歸在C++中的斐波那契(fibonacci)數(shù)列程序。

#include<iostream>    
using namespace std;      
void printFibonacci(int n){    
    static int n1=0, n2=1, n3;    
    if(n>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         cout<<n3<<" ";    
         printFibonacci(n-1);    
    }    
}    
int main(){    
    int n;    
    cout<<"Enter the number of elements: ";    
    cin>>n;    
    cout<<"Fibonacci Series: ";    
    cout<<"0 "<<"1 ";  
    printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
     return 0;  
}

執(zhí)行上面代碼得到以下結果 -

Enter the number of elements: 15 
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377