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).
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6≤ a,b ≤ 10^6. The numbers are separated by a space.
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.
-1000000 9
-999,991
两数相加([-1000000,1000000]),然后按照三位一个逗号输出,如123,456,789
两个数都不是很大,和最多是七位,所以使用int类型即可保存。
关键点解析这个数。题目要求是三位分一组,我们可以考虑使用%1000和/1000反复取得三位。然后拼在一起输出。
但是这样会出现一个小问题,就是%操作,如果得到的部分结果是两位数,此时分两种情况
(1)如果这部分是最高位,比如12345,高位%1000后是12,输出格式12,345那么这个12就是正确的,不需要处理
(2)如果这部分不是最高位,比如123045,后三位%1000后是45,输出格式123,045,这时候要考虑补0的问题。
使用一个int数组,分别纪录每一次求余的结果(也就是分段的结果),然后遍历数组即可
正数是最方便求余操作的,如果和是负数,需要取绝对值,同时使用flag纪录和的符号
#include
int main() {
int a, b, ans, k = 0, symbol = 1;
// a,b的上限是1e6,所以和的范围是[-1e7, 1e7], 数组开3个足够
int group[3];
scanf("%d", &a);
scanf("%d", &b);
ans = a + b;
// 每三个数作为一组存在数组中
// 将结果转换为绝对值,用symbol记录转换前的符号
if(ans < 0){
ans = -ans;
symbol = -1;
}
// 通过%1000 将结果分别存储在group[0], group[1] ... group[k - 1]中
//小插曲。这里必须使用do-while而不是while。以为如果两个数的和正好是0
//使用while循环的话,因为while(ans)为flase,直接跳过,此时int数组什么都没有记录,k=0
//在下面输出的时候 group[--k]会发生数组越界的段错误
do{
group[k++] = ans % 1000;
ans /= 1000;
}while (ans);
// 小于0则先输出一个负号
if(symbol == -1)printf("%c", '-');
// 输出头部
printf("%d", group[--k]);
// 输出余下部分
while (k > 0) {
// 注意输出格式
printf(",%03d", group[--k]);
}
return 0;
}