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
使用递归进行格式化输出
#include <iostream>
#include <stdio.h>
using namespace std;
void output(int n,int single,int cnt,int symbol){
if(n==0){
if(symbol==1)printf("-");
return;
}
single=n%10;
cnt+=1;
output(n/10,single,cnt,symbol);
if(cnt%3==1&&cnt!=1){
printf("%d,",abs(single));
}else{
printf("%d",abs(single));
}
}
int main(){
int a,b;
scanf("%d %d",&a,&b);
int c=a+b;
if(c<0){
output(c,0,0,1);
}else if(c==0){
printf("0");
}else{
output(c,0,0,0);
}
return 0;
}