C++ numbers add to a negative

后端 未结 2 575
鱼传尺愫
鱼传尺愫 2021-01-22 18:59

So I was just practicing coding a dynamic solution to the Fibonacci sequence which would return the n\'th Fibonacci number and I kept coming across a problem which I can\'t quit

相关标签:
2条回答
  • 2021-01-22 19:46

    Because of how C stores your int (signed int) in memory, the most significant bit indicates a negative number. So you'll get negative number if you overflow it with large numbers.

    Reference:

    • http://en.wikipedia.org/wiki/Integer_overflow
    • http://en.wikipedia.org/wiki/2%27s_complement
    0 讨论(0)
  • You need to change int to unsigned int or even better unsigned long long. Your result is overflowing the maximum value of int on your system. Because int is signed, when the most significant bit gets set, it becomes a negative number. See the Stack Overflow question titled maximum value of int, and this Swarthmore College page on binary arithmatic for more information. If you're using Visual Studio, take a look at the Data Type Ranges article on MSDN.

    In addition to switching to unsigned long long, you should probably check for overflow errors such as this and throw an exception. A revised version of your code could look like this.

    unsigned long long fib(int n) {
        vector<unsigned long long> v;
        v.push_back(1);
        v.push_back(1);
        for (int i = 2; i <= n; i++) {
            if( v.at(i-1) > (std::numeric_limits<unsigned long long>::max() - v.at(i-2)) )
                throw std::overflow_error("number too large to calculate");
            v.push_back( v.at(i-1) + v.at(i-2) );
            cout << v.at(i-1) << " + " << v.at(i-2) << " = " << (v.at(i-1) + v.at(i-2)) << endl;
        }
        return v.at(n);
    }
    

    You would also want to make sure the code calling your function can handle an exception by using a try... catch.... Here's an example

    try {
        std::cout << "2000th number = " << fib(2000) << std::endl;
    } catch( std::overflow_error& ex ) {
        std::cerr << ex.what() << std::endl; 
    }
    
    0 讨论(0)
提交回复
热议问题