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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.
Output Specification:
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的结果。
规范格式为每三个数字分为一组以逗号隔开。
输入两个大小大于 −106小于106的数字,输出结果。
题目分析
题目主要涉及对与输出结果的处理,结果分为等于零,小于零,大于零三种情况。对于等于零的情况直接输出0,对于等于零的情况需要在输出前先输出一个符号,大于零的情况正常处理。将输出结果以三个为一组存储到数组里,再依次序输出。
代码
#include "stdio.h"
int main(){
int a,b,sum1,sum2;
int c[1000000];//用于存放每组数据
int i;
scanf("%d%d",&a,&b);
sum1 = a+b;
if (sum1 == 0)
{
printf("%d",sum1);
return 0;
}//如果等于零直接输出结果。
if (sum1<0)
sum1 = -sum1;//小于零,先将其取反,最后在输出时提前输出负号。
sum2 = a+b;
for (i = 0;sum1 != 0;i++)
{
c[i] = sum1%1000;
sum1 = sum1/1000;
}//每三个数字一组,放入数组。
i = i-1;
if(sum2<0) printf("-");
printf("%d",c[i]);
if (i > 0) printf(",");
for (i = i-1;i >= 0;i--){
printf("%03d",c[i]);
if (i != 0) printf(",");
}
printf("\n");
return 0;
}