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\n", 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;
}

 

posted @ 2017-03-14 15:01  claremz  阅读(419)  评论(0编辑  收藏  举报