PAT (Advanced Level) Practice 1001 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 −10^6 ≤a,b≤ 10^6.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:

-1000000 9

Sample Output:

-999,991

题目大意

求两数之和,按照每三位一个逗号的格式进行输出。

题目分析

先计算两数之和,再转为字符串,然后按格式输出即可。
注意,从右到左每3位一个逗号,不要从左到右。

AC代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a, b, len, i;
    char s[20];
    cin >> a >> b;
    sprintf(s, "%d", a + b);
    len = strlen(s);
    for (i = 0; i < len; i++)
    {
        cout << s[i];
        if ((len - 1 - i) % 3 == 0 && i != len - 1 && !(i == 0 && s[i] == '-'))
            cout << ",";
    }
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部