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
//法一:按照要求每三位一组的输出,之要注意输出,的时机即可
#include<cstdio>
int main() {
int a, b;
scanf("%d%d", &a, &b);
int sum = a + b;
if (sum < 0) {
printf("-"); //如果是负数,先输出负号,再转为正数
sum *= -1;
}
int s[10]; //数组s储存和的每一位数字
int len = 0;
do {
s[len++] = sum % 10;
sum /= 10;
} while (sum); //用do-while而不用while是为了防止有sum = 0的情况
for (int i = len - 1; i >= 0; i--) { //因为先得到的是原数的低位,所以要逆序输出
printf("%d", s[i]);
if (i && i % 3 == 0) //第一个条件是因为当数字位数刚好是3的倍数时,最后三位数后面不用输出,
printf(",");
}
return 0;
}
//法二:利用好题目中a和b的范围,sum = a + b,则sum的范围是(2e-6)~(2e+6),那么可以根据sum的大小相应的输出,无非三种情况:(1)sum >= 1e+6,即sum位数大于6小于7,那么后6位以两组输出(即两个逗号),再输出前面多余的1位;(2)1000 <=sum <= 1e+6,,只有一个逗号,其他的直接输出(3)sum < 1000,那么sum的位数小于等于3,直接输出sum即可,没有逗号。相信意思都好理解,只是本蒻蒻文笔有限,表达的可能不是那么清晰,还请见谅!!下面是AC的代码:
#include<stdio.h>
int main() {
int a, b;
scanf("%d%d", &a, &b);
int ans = a + b;
if (ans < 0) { //对负数处理和第一种方法一样
printf("-");
ans *= -1;
}
if (ans >= 1000000) //三种可能的情况
printf("%d,%03d,%03d", ans / 1000000, ans % 1000000 / 1000, ans % 1000);
else if (ans >= 1000)
printf("%d,%03d", ans / 1000, ans % 1000);
else
printf("%d", ans);
return 0;
}