原题连接:https://www.patest.cn/contests/pat-a-practise/1001
题目如下:
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
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.
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 9Sample Output
-999,991
______________________________________________________________________________________________________________________________________________________
这道题难点在于如何三位输出,我是利用数组存放每一个数,然后倒序输出,当下标为3的倍数的时候,加入“,”,但有好几个测试点没通过……代码如下:
1 #include<stdio.h> 2 #define Max 8 3 4 int main() 5 { 6 long a,b,sum; 7 int i,c[Max]; 8 scanf("%d %d",&a, &b); 9 sum=a+b; 10 11 if (sum<0){printf("-");sum=0-sum;} 12 i=0; 13 c[i]=sum%10; 14 sum/=10; 15 while (sum>0) 16 { 17 i++; 18 c[i]=sum%10; 19 sum/=10; 20 } 21 //printf("%d ",i); 22 for (;i>=0;i--) 23 { 24 printf("%d",c[i]); 25 if (i%3==0&&i!=0)printf(","); 26 } 27 return 0; 28 }
_________________________________________________希望大神能帮我看看我的错误在哪了……
在网上参考了其他人的解法,是直接对sum这个数选取,利用了技巧:取一个数sum(假设该数共有a位)的前n位的时候,用sum/10的(a-n)次方;取它的后n位的时候,用sum%10的n次方,然后就是分情况讨论,因为题中所给a,b是在区间【-1000000,1000000】,将|sum|分为大于1000000,小于1000000而大于1000,大于等于0小于1000的。
代码如下:
1 #include<stdio.h> 2 3 int main() 4 { 5 int a,b,sum; 6 scanf("%d %d",&a,&b); 7 int i; 8 sum=a+b; 9 if (sum<0){printf("-");sum=-sum;} 10 if (sum>=1000000)printf("%d,%03d,%03d",sum/1000000,(sum/1000)%1000,(sum%1000)); 11 else if (sum>=1000)printf("%d,%03d",sum/1000,sum%1000); 12 else printf("%d",sum); 13 return 0; 14 }