PAT(A) 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.

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
using namespace std;
#include <cstdio>

//about 大整数溢出 注意long long的范围:[-2^63, 2^63) 所以可能溢出
int main()
{
    int T, num=1;
    scanf("%d", &T);
    while(T--)
    {
        long long a, b, c;     //long long 范围:[-2^53, 2^63)
        scanf("%lld%lld%lld", &a, &b, &c);     //注(1):long long 对应 %lld
        long long sum=a+b;     //注(2):a+b必须赋值给一个long long 变量再比较才能正确输出
        bool flag;          //开始判断各种情况:

        //划重点(1):当a+b>=2^63时,显然 a+b>c成立,但a+b会超过long long的正向最大值而发生正溢出
        //由范围=> a+b的最大值为2^64-2, 所以 long long存储正溢出后的值的区间为 [-2^63, -2]
     //由(2^64-2)%2^64=-2 =>右边界
if(a>0 && b>0 && sum<0) flag=true; //正溢出为true //划重点(2):当a+b<2^63时,显然 a+b<c成立,但a+b会超过long long的负向最大值而发生负溢出 //由范围=> a+b的最小值为-2^64, 所以 long long存储负溢出后的值的区间为 [0, 2^63)
     //由(-2^64)%2^64=0 =>左边界
else if(a<0 && b<0 && sum>=0) flag=false; //负溢出为false else if(sum>c) flag=true; //无溢出时,A+B>C时为true else flag=false; if(flag==true) printf("Case #%d: true ", num++); else printf("Case #%d: false ", num++); } return 0; }
原文地址:https://www.cnblogs.com/claremore/p/6548023.html