PAT1001. A+B Format
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
水题,因为题目限制在-2000000<=a+b<=2000000所以可以直接考虑小于1000,小于1000000和大于1000000三种状态的输出,不过还是决定不考虑a+b的上下限来做,思路就是先利用for循环除10判断a+b的总位数,然后设置两个数,一个用来除一个用来余。
1 #include<stdio.h> 2 #include<math.h> 3 int main() 4 { 5 int a,b,sum,abssum; 6 scanf("%d %d",&a,&b); 7 sum=a+b; 8 abssum=abs(sum); 9 int num=1,e=1,d=abssum; 10 while(d>=10) 11 { 12 num+=1; 13 d/=10; 14 } 15 while(num>3) 16 { 17 e+=1; 18 num-=3; 19 } 20 int h=1; 21 for(int i=1;i<e;i++) 22 { 23 h*=1000; 24 } 25 int k=h; 26 for(int i=0;i<e;i++) 27 { 28 if(i==0) 29 { 30 printf("%d",sum/h); 31 abssum=abs(sum%h); 32 h/=1000; 33 } 34 35 else 36 { 37 printf("%03d",(abssum%k)/h); 38 h/=1000; 39 k/=1000; 40 } 41 if(i+1!=e)printf(","); 42 } 43 }