1001 A+B Format (20分)【字符串处理】

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

解题思路:

比较简单的一道题,要求你按照格式输出给定的a,b的和,直接 上代码。

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

int main()
{
    int a,b;
    char arr[12];  //将整数转为字符数组
    int i,j;
    cin>>a>>b;
    int sum = a+b;
    if(sum<0)
    {
        sum = abs(sum);
        cout<<"-";
    }
    if(sum==0)
    {
        cout<<"0"<<endl;
    }
    else
    {
        for(i = 1,j = 1;sum!=0;i++,j++)
        {
            arr[i] = sum%10+'0';
            sum = sum/10;
            if(sum!=0&&j==3)
            {
                arr[++i] = ',';
                j = 0;
            }
        }
        for(i--;i>=1;i--)
            cout<<arr[i];
    }
    return 0;
}

 

posted @ 2020-02-24 12:01  Hu_YaYa  阅读(22)  评论(0)    收藏  举报