在整数加法中测试溢出 [英] Test for overflow in integer addition
问题描述
可能重复:
在C / C ++中检测整数溢出的最佳方法
我试图实现简单的程序,测试是否在整数加法期间发生溢出:
#include< climits>
#include< iostream>
#include< string>
using namespace std;
string overflow(long a,long b){
return((a + b)> UINT_MAX)?true:false
}
int main(){
long a,b;
cout<< enter a and b:;
cin>> a>> b;
string m = overflow(a,b);
cout<< m;
return 0;
}
UINT_MAX = 65535
所以我输入了65535和20,但它写为false为什么?
true
: (a + b)> UINT_MAX
它不能成为 true
是因为 UINT_MAX
是max,所以任何结果(a + b)
都不能大于 UINT_MAX
,因为这将是一个矛盾。
您尝试使用更大的数据类型 long
来解决这个问题,但这实际上不能保证大于C ++中的 int
。您可能希望尝试 long long
(虽然此类型在标准C ++中不存在)。
说,Java,C ++实际上没有指定每个数据类型必须是多大,所以声明 UINT_MAX = 65535
不是通用的。这只适用于无符号整数以16位保存的处理器。对于32位, UINT_MAX
是 4294967295
。
相关问题
另请参阅
Possible Duplicate:
Best way to detect integer overflow in C/C++
i have tried to implement simple program which tests if overflow occurs during integer addition:
#include <climits>
#include <iostream>
#include <string>
using namespace std;
string overflow(long a,long b){
return ((a+b)>UINT_MAX)?"true":"false";
}
int main(){
long a, b;
cout << "enter a and b: ";
cin >> a >> b;
string m = overflow(a,b);
cout << m;
return 0;
}
UINT_MAX=65535
so i have entered 65535 and 20 but it wrote false why?
Given unsigned int a, b
, this expression can never evaluate to true
:
(a+b) > UINT_MAX
The reason why it can't ever be true
is because UINT_MAX
is the max, so whatever result (a+b)
is can never be greater than UINT_MAX
, because that would be a contradiction.
You tried to use a bigger data type long
to get around this, but this is actually not guaranteed to be bigger than int
in C++. You may want to try long long
instead (although this type does not exist in standard C++).
Unlike, say, Java, C++ does not actually specify how large each data type must be, so the claim that UINT_MAX=65535
is not universally true. It's only true for processors where an unsigned integer is held in 16 bits. For 32 bits, UINT_MAX
is 4294967295
.
Related questions
See also
这篇关于在整数加法中测试溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!