1065 A+B and C (64bit) (20)(20 分)
Given three integers A, B and C in [-2^63^, 2^63^], you are supposed to tell whether A+B > C.
Input Specification:
The first line of the input gives the positive number of test cases, T (<=10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.
Output Specification:
For each test case, output in one line "Case #X: true" if A+B>C, or "Case #X: false" otherwise, where X is the case number (starting from 1).
Sample Input:
3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0
Sample Output:
Case #1: false
Case #2: true
Case #3: false
AC代码:
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
int t;
cin>>t;
long long a,b,c,result;
bool flag;
int times=1;
while(t--)
{
cin>>a>>b>>c;
result=a+b;
if(a>0&&b>0&&result<0)
flag=true;
else if(a<0&&b<0&&result>=0)
flag=false;
else if(result>c)
flag=true;
else
flag=false;
if(flag==true)
printf("Case #%d: true\n",times++);
else
printf("Case #%d: false\n",times++);
}
return 0;
}
总结:本题考察的是计算机组成原理中,浮点数加减法,正负溢出的知识,实际解题过程中我们根据浮点数不同的溢出情况构造了不同的输出分支
1.当A+B>2^63,显然,A+B>C是成立的,但发生了正溢出(因为long long 的范围是[-2^63,2^63]),A+B的最大值可能是2^64-2,那么按照正溢出的定义,会溢出到[-2^63,-2],于是我们就可以这么判定:当A>0,B>0,且A+b<0时为正溢出,输出true;
2.同上,当A+B<-2^63,A+B<C是显然的,A+B因为小于 long long 的负向最小值而发生了负溢出,A+B最小为-2^64,所以负溢出的区间是[-2^63,0]。所以我们在A<0,B<0,A+B<=0的情况下,可以认为发生负溢出,输出false
3.当不发生溢出时,就直接进行判定
ps:C语言有一个头文件叫做<limits.h>,里面对整型数据的数据类型的表达值范围有了定义,例如LLong_MAX就定义了long long 变量的最大值