A+B Format
Calcuate a + b and ouput 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: Each input file contains one test case.Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Output: 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
分析:在输出下标i的数字后,考虑((i+1)%3 == len % 3 && i != len - 1)是否成立,若成立就加上一个句号
代码:
1 #include <cstdio> 2 3 int main(){ 4 int a, b; 5 scanf("%d%d", &a, &b); 6 int sum = a + b; 7 if(sum < 0){ 8 printf("-"); 9 sum = 0 - sum; 10 } 11 int num[10]; 12 int len = 0; 13 if(sum == 0) printf("0"); 14 while(sum){ 15 num[len++] = sum % 10; 16 sum /= 10; 17 } 18 19 for(int i = 0; i < len / 2; i++){ 20 int temp = num[i]; 21 num[i] = num[len-i-1]; 22 num[len-i-1] = temp; 23 } 24 25 for(int i = 0; i < len; i++){ 26 printf("%d", num[i]); 27 if((i+1)%3 == len%3 && i != len-1){ 28 printf(","); 29 } 30 } 31 return 0; 32 }

更多精彩