-1

This is the C++ program I've written to get fibonacci numbers from 1 to 100.

#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;

int main()
{
    int n;
    vector<double> f;

    //adding first two fibonacci numbers to vector
    f.push_back(0);
    f.push_back(1);

    cout<<"How many fibonacci numbers do you want : ";
    cin>>n;

    for(int i=0; i<n; i++)
    {
        if(i>1)     f[i] = f[i-1] + f[i-2];
        cout<<(i+1)<<": "<<fixed<<setprecision(0)<<f[i]<<endl;
    }
}

All the results are correct upto 79 values but then after the 80th value is not exactly the sum of 78 and 79 values. The output is:

....
78: 5527939700884757
79: 8944394323791464
80: 14472334024676220
....

Here the last digit should be 1 but it shows 0, why did this happen?

insearchofcode
  • 438
  • 5
  • 9
  • 4
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Richard Critten Dec 14 '19 at 09:04
  • 2
    Your vector only contains two elements (the two that were pushed from inception). Indexing anything beyond that invokes *undefined behavior*. I.e. for any `i` greater than `1`, the statement `f[i] =...` is UB. – WhozCraig Dec 14 '19 at 09:10
  • The 80th Fibonacci number is a bit over `2.3E16`. Floating point variables can't accurately represent all integral values approaching that sort of magnitude. Even ignoring that, your code has undefined behaviour, because it modifies more than two elements of an array with exactly two elements. In short, your calculation is badly broken. – Peter Dec 14 '19 at 09:37

1 Answers1

1

You may not use the subscript operator for a vector element that does not yet exist in the vector.

So use for example

if(i>1) f.push_back( f[i-1] + f[i-2] );

Pay attention to that an object of the type double can be unable to store correctly all Fibonacci numbers in a given range. Instead of the type double you could use the type long double.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335