美文网首页
甲级|1065.A+B and C (64bit)

甲级|1065.A+B and C (64bit)

作者: yzbkaka | 来源:发表于2018-11-30 09:06 被阅读0次

    题目描述

    Given three integers A, B and C in [−2^​63​​, 2^​63​​], you are supposed to tell whether A+B>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).

    输入例子

    3
    1 2 3
    2 3 4
    9223372036854775807 -9223372036854775808 0

    输出例子

    Case #1: false
    Case #2: true
    Case #3: false

    我的代码

    #include<stdio.h>
    int main(){
        int t,d[100],i;
        long long a,b,c,sum;
        scanf("%d",&t);
        for(i=1;i<=t;i++){
            scanf("%lld %lld %lld",&a,&b,&c);
            sum=a+b;  //先得到a+b的和
            if(a>0&&b>0&&sum<0) d[i]=1;  //正溢出的情况
            else if(a<0&&b<0&&sum>=0) d[i]=0;  //负溢出的情况
            else if(sum>c) d[i]=1;
            else d[i]=0;
            
            if(d[i]==1){
                printf("Case #%d: true\n",i);
            }
            if(d[i]==0){
                printf("Case #%d: false\n",i);
            }
        }   
        return 0;
    } 
    

    我的分析

    这道题的题目比较简单,比较容易就可以想出算法来,但是需要将其中的细节考虑清楚,就是系统中给出的数据可能会超出范围造成溢出。溢出的情况主要是由两种,第一种是当a>0,b>0但是溢出会造成a+b<0,此时a+b一定大于c;第二种情况就是a<0,b<0但是溢出会造成a+b>=0,此时a+b一定小于c。但是在coding的过程中还是需要注意到一些细节,首先是a+b的和不能直接在if()当中进行比较,而是需要一个long long类型的数据sum先算好,之后再比较;其次是在if()与else if()的语句中,必须先判断溢出的情况,然后再是正常的判断,否则可能会造成错误。

    相关文章

      网友评论

          本文标题:甲级|1065.A+B and C (64bit)

          本文链接:https://www.haomeiwen.com/subject/bolqcqtx.html