判断两个int类型的整数相加,相减是否溢出的C语言代码

时间:2022-08-02 02:10:43
#include<stdio.h>
#include<limits.h>
int tadd_ok(int x, int y);
int tsub_ok(int x, int y);
int main()
{
printf("%d\n", tadd_ok(INT_MIN, 0));
printf("%d\n", tadd_ok(INT_MIN, -1));
printf("%d\n", tadd_ok(INT_MAX, 0));
printf("%d\n", tadd_ok(INT_MAX, 1));


printf("%d\n", tsub_ok(INT_MIN, 0));
printf("%d\n", tsub_ok(INT_MIN+3, 5));
printf("%d\n", tsub_ok(0, INT_MIN));
printf("%d\n", tsub_ok(1, INT_MIN));
return 0;
}
int tadd_ok(int x, int y)    //判断两个数相加是否溢出,溢出就返回0
{
int sum = x + y;
if(x > 0 && y > 0)
{
if(sum < 0)   //正溢出
return 0;
else
return 1;
}
else if(x < 0 && y < 0)
{
if(sum >= 0)   //负溢出
return 0;
else
return 1;
}
else
return 1;
}
int tsub_ok(int x, int y)   //判断两个数相减是否溢出,溢出就返回0
{
int diff = x - y;
if(y != INT_MIN)
{
if(x > 0 && y < 0)
{
if(diff < 0)
return 0;
else
return 1;
}
else if(x < 0 && y > 0)
{
if(diff > 0)   //负溢出
return 0;
else
return 1;
}
else
return 1;
}
else
{
if(x > 0)  //正溢出
return 0;
else
return 1;
}

}