数组中正值的总和在c程序中给出负结果 [英] Sum of positive values in an array gives negative result in a c program

查看:78
本文介绍了数组中正值的总和在c程序中给出负结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,就是当我对一个数组的值求和(全部为正,我通过打印该数组的值进行验证)时,我最终得到一个负值.我的总和代码为:

I have a problem that is, when I sum the values of an array (that are all positive, I verified by printing the values of the array), I end up with a negative value. My code for the sum is:

int summcp = 0;
for (k = 0; k < SIMUL; k++)
{
    summcp += mcp[k];
}
printf("summcp: %d.\n", summcp);`

任何有关此问题的提示将不胜感激.

Any hint about this problem would be appreciated.

推荐答案

您正在调用未定义的行为.

由于整数变量只能容纳有限的值范围,因此标准未定义超出该范围.基本上任何事情都可能发生.在您(也是最常见的情况)下,它只是将其二进制表示形式包装起来.因为它用于负值,所以您将这样阅读.

As integer variables can only hold a limited range of values, going beyond this range is undefined by the standard. Basically anything can happen. In your (and the most common) case, it simply wraps around its binary representation. As this is used for negative values, you will read this as such.

要避免这种情况,请为summcp使用一种类型,该类型可以容纳所有个可能的值.一种替代方法是通过以下方法检查下一个添加项是否溢出:

To circomvent this, use a type for summcp which can hold all possible values. An alternative would be to check if the next addition will overflow by:

if ( summcp >= INT_MAX - mcp[k] ) {
    // handle positive overflow
}

请注意,以上内容仅适用于mcp[k] >= 0和正溢出.其他3种情况必须以不同的方式处理.通常,最好使用一种足够大的类型进行求和,然后再进行溢出测试(如果需要),这样最好,更快,更容易.

Note that the above only works for mcp[k] >= 0 and positive overflow. The other 3 cases have to be handled differently. It is in general best, faster and much easier to use a large enough type for the sum and test lateron for overflow, if required.

不要试图添加和测试结果!由于整数溢出是未定义的行为,因此并非所有架构都适用.

Do not feel tempted to add and test the result!. As integer overflow is undefined behaviour, this will not work for all architectures.

这篇关于数组中正值的总和在c程序中给出负结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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