1. The first version of the program
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. The second version
BOOL Fib (int pos, int &elem)
{
if (pos < 0 | | pos > 1024)
{
elem = 0;
return false;
}
Elem = 1; Note: The definition can only be 1 times
int n1 = 1, N2 = 1;
for (int i = 3; I <= pos; i++)
{
Elem = n2 + n1;
N1 = n2;
N2 = Elem;
}
return true;
}
Main function call
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. Third version of the improved 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;
}
Main function call
Const vector<int> *result=fib_new (5);
cout << result->back ();
Const vector<int> *result=fib_new (5);
cout << Result->at (4) << Endl;
How many times this should be called back, this is not clear, leave a mark.
This last version avoids repeated operations and uses a local static object.