PAT1001. A+B Format

题目

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 Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

Output Specification:

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:

1
-1000000 9

Sample Output:

1
-999,991

分析

使用递归按照1000不断分离数位,先打印高位,然后补逗号继续打印后三位。 要注意的地方:中间要打印的数可能不满三位,需要在左边用0补足,printf("%0md");m为总共要输出的位数,0表示前面补0。还有就是区间的问题,开始一个>1000,一个<1000忘了考虑1000的情况直接没输出。第一次做PAT有点儿郁闷。

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdio>
#include <cstdlib>

void printc(int c)
{
    if (abs(c)<1000)
        printf("%d",c);
    else if(abs(c)>=1000)
    {
        printc(c/1000);

        printf(",%03d",abs(c%1000));
    }
}
int main() {
    int a,b;
    scanf("%d %d",&a,&b);
    printc(a+b);

    return 0;
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计