题目要求:
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
算法思想:
本题的难点在于结果的情况多样。
- 正负问题,(小于的时候输出符号,其余操作按正数进行)
- fabs(结果)是否超过三位,如果没有直接输出
- 超过三位时,用数组每隔三位进行存储。然后逆序输出。
- 此时,除最高位外,位数不足三位的要在前面补0输出。
代码展示:
#include <cstdio>
#include <cmath>
int main(){
int a,b;
scanf("%d %d",&a,&b);
int c = a+b;
if(c<0)
printf("-");
int te = fabs(c);
int temp[10]={0};
int i= 0;
if(te>1000){
while(fabs(te)){
temp[i] = te % 1000;
te /= 1000;
i++;
}
i--;
if(temp[i]!= 0){
printf("%d,",temp[i]);
i--;
}
for(int j=i;j>0;j--){
if(temp[j]>=100)
printf("%d,",temp[j]);
else if (temp[j]>=10)
printf("0%d,",temp[j]);
else{
printf("00%d,",temp[j]);
}
}
if(temp[0]>=100)
printf("%d",temp[0]);
else if (temp[0]>=10)
printf("0%d",temp[0]);
else{
printf("00%d",temp[0]);
}
}
else{
printf("%d",te);
}
printf("\n");
return 0;
}