Weird output as the numbers get bigger in Fibonacci sequence

Posted by Jon on Stack Overflow See other posts from Stack Overflow or by Jon
Published on 2013-06-24T16:18:15Z Indexed on 2013/06/24 16:21 UTC
Read the original article Hit count: 79

Filed under:

I noticed in my fibonacci sequence that I'm getting negative numbers after a certain point. Does this have to do with the limited range of "int"? or is there something wrong with my code?

Here is the code:

using std::cout;

int main()
{

int n = 50, f1 = 0, f2 = 1, fn = 0, i = 0;

cout << "0 ";
for (i = 0; i < n; i++)
{
    fn = f1 + f2;
    f2 = f1;
    f1 = fn;

    cout << fn << " ";
}

© Stack Overflow or respective owner

Related posts about c++