Given three integers A, B and C in [−263,263], you are supposed to tell whether A+B>C.c++
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.数组
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).ide
3 1 2 3 2 3 4 9223372036854775807 -9223372036854775808 0
Case #1: false Case #2: true Case #3: false
因为long long的范围是[-263, 263),所以题目中给出的两个整数相加有可能会溢出(正溢出或负溢出),直接进行大小判断会形成错误。在计算机组成原理中会指出,若是两个正数之和等于负数或是两个负数之和等于正数,那么就是溢出。测试
对于溢出后的具体范围,能够进行以下分析:
①当A+B≥2^63时,显然有A+B>C成立,但A+ B会因超过long long的正向最大值而发生正溢出。因为题目给定的A和B最大均为263-1,故A+B最大为264-2,所以使用long long存储正溢出后的值的区间为[-263, -2] (由(264 - 2)%(264)= -2可得右边界)。因此,当A>0,B>0,A+B<0时为正溢出,输出true。
②当A+B<-263时,显然有A+B<C成立,但A+ B会因超过long long的负向最小值而发生负溢出。因为题目给定的A和B最小均为263,故A+ B最小为264,所以使用longlong存储负溢出后的值的区间为[0, 263) (由( -264)%264=0可得左边界)。因此,当A<0,B<0,A+ B≥0时为负溢出,输出false.
③在没有溢出的状况下,当A+B>C时,输出true; 当A+B≤C时,输出false.spa
#include<stdio.h> int main(){ int t; scanf("%d", &t); long long a[10], b[10], c[10]; for(int i = 0; i < t; i++){ scanf("%lld %lld %lld", &a[i], &b[i], &c[i]); } for(int i = 0; i < t; i++){ long long sum; sum = a[i] + b[i]; if(a[i] > 0 && b[i] > 0 && sum < 0) printf("Case #%d: true\n", i + 1); else if(a[i] < 0 && b[i] < 0 && sum >= 0) printf("Case #%d: false\n", i+1); else if(sum > c[i]) printf("Case #%d: true\n", i + 1); else printf("Case #%d: false\n", i + 1); } return 0; }
2号:更加简单,其实不须要用数组,在循环的时候就有i能够引用code
#include <cstdio> using namespace std; int main() { int n; scanf("%d", &n); for(int i = 0; i < n; i++) { long long a, b, c; scanf("%lld %lld %lld", &a, &b, &c); long long sum = a + b; if(a > 0 && b > 0 && sum < 0) { printf("Case #%d: true\n", i + 1); } else if(a < 0 && b < 0 && sum >= 0){ printf("Case #%d: false\n", i + 1); } else if(sum > c) { printf("Case #%d: true\n", i + 1); } else { printf("Case #%d: false\n", i + 1); } } return 0; }