1 有符号数相加溢出判断
1.1 两个有符号的数是正数
当两个有符号整数x,y
同为正数,且x+y
的结果为非正时,发生了正溢出。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
int x;
int y;
scanf("%d %d", &x, &y);
int s = x + y;
if (x > 0 && y > 0 && s < 0) {
cout << "发生了正溢出:符号位的1被覆盖为0" << endl;
}
else {
cout << "没有溢出" << endl;
}
system("pause");
return 0;
}
测试(1)
测试(2)
1.2 两个有符号的数是负数
当两个有符号整数x,y
同为负数,且x+y
的结果为非负时,发生了负溢出。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
int x;
int y;
scanf("%d %d", &x, &y);
int s = x + y;
if (x < 0 && y < 0 && s > 0) {
cout << "发生了负溢出:符号位的1被覆盖为0" << endl;
}
else {
cout << "没有溢出" << endl;
}
system("pause");
return 0;
}
测试(1)
测试(2)
1.3 两个有符号的数是一正一负
一个加数为正,另一个加数为负,或者任意一个加数为0时,不可能有溢出发生。
2 无符号数相加溢出判断
当两个无符号整数x,y
的和s
小于x
或y
时,发生了溢出。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
uint16_t x;
uint16_t y;
cin >> x >> y;
uint16_t s = x + y;
if (s < x) {
cout << "发生了溢出:进位被丢弃" << endl;
} else if (s < y) {
cout << "发生了溢出:进位被丢弃" << endl;
}
else {
cout << "没有溢出" << endl;
}
system("pause");
return 0;
}
测试(1)
测试(2)
测试(3)
发生溢出后,和s
小于任何一个加数x或者y
,因此拿任何一个判断均可。