zoukankan      html  css  js  c++  java
  • PAT(A) 1001. A+B Format (20)

    Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

    Input

    Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

    Output

    For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

    Sample Input

    -1000000 9
    

    Sample Output

    -999,991
    
    #include <cstdio>
    
    int main()
    {
        int a, b ,sum;
        int num[10];    //存放转化成字符串的sum(a, b < 10^9 => 数组范围 10)
        scanf("%d%d", &a, &b);
        sum=a+b;
        if(sum<0{      //sum为负数时,输出负号并取sum的相反数
            printf("-");
            sum=-sum;
        }
    
    /*  //法一:
        int len=0;      //len存放sum的长度
        do{             //划重点(1):将数字分解再存放于字符串中
            num[len++]=sum%10;
            sum /= 10;
            //printf("%d %d
    ", sum, len);  //debug
        }while(sum);    //此时eg. sum=123 => num[]=321(即为逆序存放)
        for(int i=len-1; i>=0; i--){
            printf("%d", num[i]);
            //每三位一个逗号(i%3==0),最后一位除外(i>0)   eg. 012345678 => 876,543,210
            if(i>0 && i%3==0)   printf(",");
        }
    */
        //法二: 利用sum<10^9 *2 => sum最多9位
        //划重点(2): printf的格式化输出中,%3d表示输出三位整数,不满三位得的高位补空格
        //                             %03d表示输出三位整数,不满三位的高位补0
        if(sum>=1000000)
            printf("%d,%03d,%03d", sum/1000000, sum%1000000/1000, sum%1000);
        else if(sum>=1000)
            printf("%d,%03d", sum/1000, sum%1000);
        else
            printf("%d", sum);
    
        return 0;
    }
  • 相关阅读:
    服务器又100%了,上一个挖矿病毒解决完,这几天又来了一个新的挖矿病毒。。。。
    一些面试题
    家庭应急储备物资分类
    所学习的docker
    Mysql主从复制原理及同步延迟问题
    关于git
    小程序的get和post需要注意的地方
    CSS3 3D转换
    transform CSS3 2D知识点汇总
    HTML5基础知识总结(一)
  • 原文地址:https://www.cnblogs.com/claremore/p/6548547.html
Copyright © 2011-2022 走看看