1.题目描述
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
2.解题过程
本题并没有涉及大数加减法,只是在输出时需要注意从各位起,每三位添加一个‘,’分割,因此将计算的结果放到字符数组中并添加‘,’。
需要注意的是最高为不要多输出‘,’,另外要特别处理和为0的情况。
代码如下:
/*A1001*/
#include<cstdio>
#include<cstring>
#define NUM 10
int main(){
int a,b,sum,count=0,i=0,count2=0;;
char ans[NUM];
scanf("%d%d",&a,&b);
sum = a + b;
if(sum<0){
printf("-");
sum = -sum;
}
if(sum==0){
ans[0] = 0;
printf("0");
}
else{
while(sum){
ans[i] = sum%10 + '0';
i++;
count++;
count2++;
sum = sum/10;
if(count%3==0&&sum){
ans[i] = ',';
i++;
count2++;
}
}
}
for(int j=count2-1;j>=0;j--){
printf("%c",ans[j]);
}
return 0;
}