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;
}
//Method 2: Make good use of the range of a and b in the title , sum = a + b, then the range of sum is (2e-6)~(2e+6), then the output can be based on the size of sum, nothing more than three Two situations : (1) sum >= 1e+6 , that is, the number of sum digits is greater than 6 and less than 7, then the last 6 digits are output in two groups (that is, two commas), and then the extra 1 digit in front is output; (2) 1000 < =sum <= 1e+6 , there is only one comma, and the others will directly output (3) sum <1000 , then the digits of sum are less than or equal to 3, just output sum directly without commas. I believe that the meaning is easy to understand , but the writing style of this 蒻蒻 is limited, and the expression may not be so clear. Please forgive me! ! Here is the code of 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;
}