国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++求Fib數列

2020-01-26 14:42:52
字體:
來源:轉載
供稿:網友

1. 第一版本程序

int fib(int pos)  {    int elem = 1;    int n1 = 1, n2 = 1;    for (int i = 3; i <= pos; i++)    {      elem = n2 + n1;      n1 = n2;      n2 = elem;    }    return elem;  }

2. 第二版本

bool fib(int pos, int &elem)  {    if(pos < 0 || pos > 1024)    {      elem = 0;      return false;    }    elem = 1; //注意:定義只能有1次    int n1 = 1, n2 = 1;    for (int i = 3; i <= pos; i++)    {      elem = n2 + n1;      n1 = n2;      n2 = elem;    }    return true;  }

主函數調用

int main()  {        int pos;    cout <<"Please enter a position: ";    cin >> pos;      int elem;    if(fib(pos, elem))    {      cout << "element # " << pos         << " is " << elem << endl;    }    else      cout << "Sorry. Couldn't calculate element #"         << pos <<endl;  }

3. 第三版本 改進后的fib

const vector<int>* fib_new(int size)  {    const int max_size = 1024;    static vector<int> elems;      if(size <= 0 || size >= max_size)    {      cerr << "fib_new(): oops:invalid size:"         << size << "-- can't fulfill request./n";      return 0;    }    for(int ix = elems.size(); ix < size; ix++)    {      if (ix == 0 || ix == 1)        elems.push_back(1);      else        elems.push_back(elems[ix - 1] + elems[ix - 2]);    }    return &elems;  }

主函數調用

    const vector<int> *result=fib_new(5);    cout << result->back();        const vector<int> *result=fib_new(5);    cout << result->at(4)<< endl;    //這個應該怎么多次調用返回,這個還沒明白,留個記號。

最后這個版本可以避免進行重復運算,使用了局部靜態對象。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 惠水县| 陇南市| 丹东市| 清远市| 屯留县| 侯马市| 达尔| 柞水县| 合肥市| 天镇县| 沅江市| 宜君县| 徐闻县| 乡城县| 常州市| 东乡县| 涡阳县| 玛多县| 江孜县| 兴文县| 施甸县| 班玛县| 平果县| 兴安县| 久治县| 集贤县| 新密市| 杨浦区| 汶上县| 岑溪市| 临高县| 百色市| 江永县| 缙云县| 浑源县| 巧家县| 侯马市| 昆山市| 竹山县| 怀安县| 松滋市|