C ++数字加到负数 [英] C++ numbers add to a negative

查看:51
本文介绍了C ++数字加到负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我只是在练习对斐波那契序列的动态解进行编码,该解决方案将返回第n个斐波那契数,所以我一直遇到一个我不太想知道的问题.我得到两个正数加一个负数!

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 quite figure out. I am getting two positive numbers adding to a negative!

代码:

int fib(int n) {
    vector<int> v;
    v.push_back(1);
    v.push_back(1);
    for (int i = 2; i <= n; i++) {
        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);
}

尝试运行fib(50),请注意cout仅用于调试

try running fib(50), note cout is just for debugging

推荐答案

您需要将 int 更改为 unsigned int 甚至更好的 unsigned long long .您的结果溢出了系统上 int 的最大值.由于 int 已签名,因此当设置最高有效位时,它变成一个负数.请参阅标题为 int的最大值的Stack Overflow问题,以及位于二进制算术了解更多信息.如果您使用的是Visual Studio,请查看

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.

除了切换到 unsigned long long 外,您可能还应该检查诸如此类的溢出错误并引发异常.您的代码的修订版可能如下所示.

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);
}

您还需要确保使用 try ... catch ... 来调用函数的代码可以处理异常.这是一个例子

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; 
}

这篇关于C ++数字加到负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆