I was writing a program in C++ to find all solutions of ab = c, where a, b and c together use all the digits 0-9 exactly once. The program looped over values of a and b, and it ran a digit-counting routine each time on a, b and ab to check if the digits condition was satisfied.
However, spurious solutions can be generated when ab overflows the integer limit. I ended up checking for this using code like:
unsigned long b, c, c_test;
...
c_test=c*b; // Possible overflow
if (c_test/b != c) {/* There has been an overflow*/}
else c=c_test; // No overflow
有没有更好的方法来测试溢出?我知道有些芯片有一个内部标志,在发生溢出时会设置该标志,但我从未见过它通过 C 或 C++ 访问。
当心signed int
溢出是 C 和 C++ 中未定义的行为,因此你必须检测它而不实际引起它。对于加法之前的signed int 溢出,请参见检测 C/C++ 中的有符号溢出.
我发现您正在使用无符号整数。根据定义,in C(我不了解 C++),无符号算术不会溢出...所以,至少对于 C,你的观点是没有意义的:)
对于有符号整数,一旦出现溢出,未定义的行为(UB) 已经发生,并且您的程序可以执行任何操作(例如:渲染测试不确定)。
#include <limits.h>
int a = <something>;
int x = <something>;
a += x; /* UB */
if (a < 0) { /* Unreliable test */
/* ... */
}
要创建合格的程序,您需要测试溢出before产生所述溢出。该方法也可以用于无符号整数:
// For addition
#include <limits.h>
int a = <something>;
int x = <something>;
if (x > 0 && a > INT_MAX - x) // `a + x` would overflow
if (x < 0 && a < INT_MIN - x) // `a + x` would underflow
// For subtraction
#include <limits.h>
int a = <something>;
int x = <something>;
if (x < 0 && a > INT_MAX + x) // `a - x` would overflow
if (x > 0 && a < INT_MIN + x) // `a - x` would underflow
// For multiplication
#include <limits.h>
int a = <something>;
int x = <something>;
// There may be a need to check for -1 for two's complement machines.
// If one number is -1 and another is INT_MIN, multiplying them we get abs(INT_MIN) which is 1 higher than INT_MAX
if (a == -1 && x == INT_MIN) // `a * x` can overflow
if (x == -1 && a == INT_MIN) // `a * x` (or `a / x`) can overflow
// general case
if (x != 0 && a > INT_MAX / x) // `a * x` would overflow
if (x != 0 && a < INT_MIN / x) // `a * x` would underflow
对于除法(除了INT_MIN
and -1
特殊情况),没有任何超越的可能性INT_MIN
or INT_MAX
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)