• 文章
  • 用於生成斐波那契數列的 C++ 類
釋出
2016年8月9日 (最後更新:2016年8月9日)

用於生成斐波那契數列的 C++ 類

評分:3.6/5 (723 票)
*****

斐波那契類

斐波那契數列以義大利數學家比薩的列奧納多(人稱斐波那契)的名字命名。他在1202年出版的《計算之書》(Liber Abaci)將此數列引入西歐數學,儘管該數列在印度數學中早有記載,被稱為“維拉漢卡數”。按照慣例,該數列從 F₀=0 或 F₁=1 開始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

using namespace std;

class Fibonacci{
public:
    int a, b, c;
    void generate(int);
};

void Fibonacci::generate(int n){
    a = 0; b = 1;
    cout << a << " " <<b;
    for(int i=1; i<= n-2; i++){
        c = a + b;
        cout << " " << c;
        a = b;
        b = c;
    }
}

int main()
{
    cout << "Hello world! Fibonacci series" << endl;
    cout << "Enter number of items you need in the series: ";
    int n;
    cin  >> n;
    Fibonacci fibonacci;
    fibonacci.generate(n);
    return 0;
}

附件:[main.cpp]