1. 第一版本程序
1
2
3
4
5
6
7
8
9
10
11
12
|
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. 第二版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 ; } |
主函数调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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; } |
主函数调用
1
2
3
4
5
6
|
const vector< int > *result=fib_new(5); cout << result->back(); const vector< int > *result=fib_new(5); cout << result->at(4)<< endl; //这个应该怎么多次调用返回,这个还没明白,留个记号。 |
最后这个版本可以避免进行重复运算,使用了局部静态对象。