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;
    }
  • 相关阅读:
    编译KlayGE所需要的第三方库和工具下载
    KlayGE启用顶级域名
    Sophus和Eigen 李群李代数 简单介绍
    G2O曲线拟合1
    梯度下降
    PCL1.8单张图点云转换显示
    双目测距demo
    Kinect基于微软SDK彩图与深度图对齐
    单例模式
    zendstudio卡死
  • 原文地址:https://www.cnblogs.com/claremore/p/6548547.html
Copyright © 2011-2022 走看看