zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++生成斐波拉其数列

C++ 生成 数列
2023-09-27 14:28:09 时间

该方法作为一种演示功能左右,运行较慢。

#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;
}