PAT1001 A+B Format HERODING的PAT之路

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

题目大意:
计算A+B的和,然后从个位开始每三位输出一个‘,’(标准格式输出)

解题思路:
通过了解题目大意就可以知道解决这道题还需要字符串处理操作,首先就是计算,因为位数少直接上int即可,把计算结果保存为string类型,按顺序输出,在输出过程中要判断位数,如果当前位数模3余1且不是个位,那么在这后面输出‘,’,代码如下:

#include<iostream>
using namespace std;

int main() {
    
    
    int a, b;
    cin >> a >> b;
    string res = to_string(a + b);
    int len = res.length();
    for(int i = 0; i < len; i ++) {
    
    
        cout << res[i];
        if(res[i] == '-') continue;
        if((len - i) % 3 == 1 && i != len - 1) cout << ",";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/114090537
今日推荐