PAT-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 −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:

-1000000 9

Sample Output:

-999,991

Code

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    
    int a,b;
    cin>>a>>b;
    if(a+b<0)   cout<<"-";
    string temp = to_string(abs(a+b));
    int i=temp.size()%3==0?3:temp.size()%3; // 注意,如果余数是0,那么输出前面的3个数
    cout<<temp.substr(0,i);
    for(; i<temp.size(); i+=3){
    
    
        cout<<","<<temp.substr(i,3);
    }
    return 0;
}
/*
字符串的长度取模3,如果余数为0,那么输出3个数字
如果余数为1,那么输出1个数字,
如果余数为2,那么输出2个数字,
剩下的数字,按照3个数字输出并且输出,
*/

Guess you like

Origin blog.csdn.net/weixin_42100456/article/details/108654397