题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1065
溢出
当a,b同号时才会发生溢出。
表1
a | b | a+b |
- | - | + |
+ | + | - |
示例代码:
#include <stdio.h>
int main()
{
int a = 2000000000;
int b = 2000000000;
printf("%d\n", a+b);
return 0;
}
结果:
-294967296
溢出检测方法
按表1,可以对结果进行判断,具体不再示例。另外,可以使用limits.h中的数据进行判断。代码(1),使用该方法。代码(2)使用以上讲的检测方法,但有部分测试点,不通过。
题目代码(1):
#include <stdio.h>
#include <limits.h>//定义了不同数据类型的数据范围
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
long long int a, b, c;
int t;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
scanf("%lld%lld%lld", &a, &b, &c);
//printf("%lld %lld %lld\n", a, b, c);
bool flag;
if(a>0 && b>0 && a > LLONG_MAX-b)
{
flag = true;//a+b溢出
}
else if(a<0 && b<0 && a < LLONG_MIN-b)
{
flag = false;
}
else
{
flag = a+b>c;
}
printf("Case #%d: ", i);
printf(flag == true ? "true\n":"false\n");
}
return 0;
}
题目代码(2)
//2个测试点错误!
#include <stdio.h>
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
long long int a, b, c;
int t;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
scanf("%lld%lld%lld", &a, &b, &c);
//printf("%lld %lld %lld\n", a, b, c);
bool flag;
if(a>0 && b>0 && a+b<0)
{
flag = true;//a+b溢出
}
else if(a<0 && b<0 && a+b>0)
{
flag = false;
}
else
{
flag = a+b>c;
}
printf("Case #%d: ", i);
printf(flag == true ? "true\n":"false\n");
}
return 0;
}
代码(3)
采用temp临时存储a+b后就正确了,为啥呢?
#include <stdio.h>
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
long long int a, b, c;
int t;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
scanf("%lld%lld%lld", &a, &b, &c);
//printf("%lld %lld %lld\n", a, b, c);
bool flag ;
long long temp = a+b;
if(a>0 && b>0 && temp <= 0)
{
flag = true;//a+b溢出
}
else if(a<0 && b<0 && temp >= 0)
{
flag = false;
}
else
{
flag = temp > c;
}
printf("Case #%d: ", i);
printf(flag == true ? "true\n":"false\n");
}
return 0;
}