如何检查A + B是否过长? (A和B都很长很长) [英] How do I check if A+B exceed long long? (both A and B is long long)

查看:147
本文介绍了如何检查A + B是否过长? (A和B都很长很长)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字: A B 。我需要在代码中的某处计算 A + B A B 都是 long long ,他们可以是正面还是负面

I have two numbers: A and B. I need to calculate A+B somewhere in my code. Both A and B are long long, and they can be positive or negative.

我的代码运行错误,我怀疑在计算 A + B <时出现问题/ code>。我只是想检查 A + B 是否超过 long long 个范围。因此,任何方法都是可以接受的,因为我仅将其用于调试。

My code runs wrong, and I suspect the problem happens when calculating A+B. I simply want to check if A+B exceed long long range. So, any method is acceptable, as I only use it for debug.

推荐答案

仅当两个数字相同时才可能溢出标志。如果两者均为正,则数学上 A + B> LLONG_MAX 或等价的 B> LLONG_MAX-A 。由于右手边为非负数,因此后一种情况已经暗示 B> 0 。类似的论点表明,对于否定情况,我们也无需检查 B 的符号(由于 Ben Voigt 指出,不需要对 B 进行符号检查)。然后,您可以检查

Overflow is possible only when both numbers have the same sign. If both are positive, then you have overflow if mathematically A + B > LLONG_MAX, or equivalently B > LLONG_MAX - A. Since the right hand side is non-negative, the latter condition already implies B > 0. The analogous argument shows that for the negative case, we also need not check the sign of B (thanks to Ben Voigt for pointing out that the sign check on B is unnecessary). Then you can check

if (A > 0) {
    return B > (LLONG_MAX - A);
}
if (A < 0) {
    return B < (LLONG_MIN - A);
}
return false;

检测溢出。这些计算不会因初始检查而溢出。

to detect overflow. These computations cannot overflow due to the initial checks.

检查 A + B 结果的符号是否可行具有保证整数溢出的环绕语义。但是有符号整数的溢出是未定义的行为,即使在实现了折回的行为的CPU上,编译器也可能会假定没有未定义的行为发生,并在实现后完全删除溢出检查。因此,对问题的评论中建议的检查非常不可靠。

Checking the sign of the result of A + B would work with guaranteed wrap-around semantics of overflowing integer computations. But overflow of signed integers is undefined behaviour, and even on CPUs where wrap-around is the implemented behaviour, the compiler may assume that no undefined behaviour occurs and remove the overflow-check altogether when implemented thus. So the check suggested in the comments to the question is highly unreliable.

这篇关于如何检查A + B是否过长? (A和B都很长很长)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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