题目
=================================================
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
思路
=================================================
注意如果是六位数字,不能在开头加逗号。如,999,999
完整代码
=================================================
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
void deal(int x){
char ans[105];
int len = 0;
int tlen = 0;
char c;
bool t = false;
if(x == 0){
cout << "0";
return;
}
if(x < 0){
x = 0 - x;
cout << "-";
}
while(1){
if(t){
tlen++;
ans[len++] = ',';
t = false;
}
c = x % 10 + '0';
x /= 10;
ans[len++] = c;
if((len - tlen) % 3 == 0){
t = true;
}
if(x == 0)break;
}
for(int i = len - 1; i >= 0; i--){
cout << ans[i];
}
}
int main() {
int a, b;
int sum = 0;
while(cin >> a >> b){
sum = a + b;
deal(sum);
}
return 0;
}