1065 A+B and C (64bit) (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
题意:
给出三个大整数A,B,C,如果A+B>C,则输出 ture,否则输出false。
思路:
由题意给出的A,B,C的范围可知,A,B,C应存放于long long型变量中,另外A+B还有可能超出long long 型整数表示范围即溢出,不能简单的靠>来判断。由计算机组成原理中数据表示和运算相关知识可知,补码溢出判断方法有三种,这里采用单符号位法,即参加操作的两个数符号相同,结果却于原操作数符号不同,则代表溢出。
若A>0,B>0,而D=A+B<0,正溢出,则说明实际运算结果肯定大于C(已经超过C可表示的最大值);
若A<0,B<0,而D=A+B>0,负溢出,则说明实际运算结果肯定小于C(已经超过C可表示的最小值);
若无溢出,D=A+B>C,说明A+B确实大于C;
若无溢出,D=A+B<C,说明A+B确实小于C;
最后按格式输出即可。
参考代码:
#include <cstdio>
int main(){
int T;
scanf("%d",&T);
int count=1;
for (int i=0;i<T;i++){
long long A,B,C;
scanf("%lld %lld %lld",&A,&B,&C);
long long D=A+B;//存放A+B的结果,有可能超过long long的表示范围;
bool flag;
if(A>0&&B>0&&D<0) flag=true;//正溢出;
else if(A<0&&B<0&&D>=0) flag=false; //负溢出;
else if (D>C) flag=true;//无溢出;
else flag=false; //无溢出;
if(flag==true) printf("Case #%d: true\n",count++);
else printf("Case #%d: false\n",count++);
}
return 0;
}
点评:
①此题属于简单模拟型,英文题意也较好理解,按题意翻译即可。
②注意题中给出数据的范围选取合适类型变量,还要注意数据经运算后是否还满足原变量类型表示范围,若不满足则要更换数据类型,甚至判断溢出情况。
③在此给出补码定点数加减运算溢出判断的三种方法。
方法 | 溢出判断条件 |
---|---|
单符号法 | 参加操作的两个数符号相同,而结果又与原操作数符号不同,表示溢出 |
双符号位法 | 运算结果的两个符号位相同,表示未溢出,不同表示溢出,其中最高符号位代表真正的符号 |
符号位和进位法 | 若符号位的进位与最高数位的进位相同,则表示没有溢出,否则表示溢出 |