C++ numbers add to a negative

后端 未结 2 603
鱼传尺愫
鱼传尺愫 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:52

    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 v;
        v.push_back(1);
        v.push_back(1);
        for (int i = 2; i <= n; i++) {
            if( v.at(i-1) > (std::numeric_limits::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; 
    }
    

提交回复
热议问题