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
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格式化
计算a+b并且以标准格式输出他们的和,数字必须用逗号分成三个一组(除非不到4个数字)
输入:
每个输入文件包含一个实例。每个样例包含一对数字a和b,a和b范围是 - 1000000 <= a, b <= 1000000。这两个数字用空格分开。
输出:
对于每一个实例,你要在一行中输出a和b的和。和必须用标准格式书写。
样例输入:
- 1000000 9
样例输出:
- 999, 991
分析:我们可以分成两步来完成。第一步,先把a与b的和转化成一个字符串。第二步,从个位数开始,每3个数字插入一个逗号,要注意的是不能在最前端加逗号。
另外为了不分正负讨论,对于负数,我们可以输出负号,然后再把负号从字符串中抹去。
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int main()
{
int a, b, i;
cin >> a >> b;
char c[10];
sprintf(c, "%d", a + b);
string s = c;//数字转字符串
string temp = ",";//temp字符串代表逗号
if (a + b < 0) //如果和小于0
{
cout << "-";//先输出负号
s.erase(0, 1);//再把负号抹去
}
for (i = s.length() - 3; i > 0; i -= 3)//从倒数第3个字符开始,每隔3个插入一个逗号
s.insert(i, temp);
cout << s;
}