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 −10?6??≤a,b≤10?6. 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两个数 限制为 −10?6??≤a ,b≤10?6 ,然后按照国际标准给数字填上,我偷了个懒, A, B整型输入, 和存储在字符串里,然后%c一个个输出
这里需要注意几个输出点:
- 最后一位,不需要判断
- 如果和小于0,那么需要跳过‘-’
- 注意数组大小,记得考虑进位和‘\0’以及‘-’
AC代码如下:
−10?6??≤a,b≤10?6#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char str[9]; int A, B; scanf("%d %d", &A, &B); sprintf(str, "%d", (A + B)); int len = strlen(str); for (int i = 0; i < len; i++) { printf("%c", str[i]); if (len - 1 == i || ‘-‘ == str[i]) { continue; } if (0 == (len - 1 - i) % 3) { printf(","); } } return 0; }