【PAT】1065. A+B and C (64bit) (20)
題目描述
Given three integers A, B and C in [-263, 263], you are supposed to tell whether A+B > C.
翻譯:給你桑整數A,B,C 範圍在[-2^63, 2^63]之間,你需要輸出A+B是否大於C。
INPUT FORMAT
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.
翻譯:輸入第一行為測試資料的組數T(<=10)。接著T組測試資料,每組包括一行三個整數A,B,C,之間用空格隔開。
OUTPUT FORMAT
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).
翻譯:對於每組輸入資料,輸出一行”Case #X: true”如果A+B>C,否則輸出”Case #X: false” ,X為測試資料的次數。
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要先儲存到一個long long int型別變數中,否則資料仍按照int進行計算。資料需要判斷溢位,即A>0&&B>0但是C<0,這種情況一定是true;A<0&&B<0但是A+B>=0,這種情況一定是false,注意負負相加可以為0。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
long long int A,B,C;
int main(){
int T;
scanf("%d",&T);
for(int i=1;i<=T;i++){
scanf("%lld%lld%lld",&A,&B,&C);
long long int sum=A+B;
printf("Case #%d: ",i);
if(A<0&&B<0&&sum>=0)printf("false\n");
else if(A>0&&B>0&&sum<0)printf("true\n");
else if(sum<=C)printf("false\n");
else if(sum>C)printf("true\n");
}
return 0;
}