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 9
Sample Output
-999,991 

water questions, because the questions are limited to -2000000<=a+b<=2000000, you can directly consider the output of three states of less than 1000, less than 1000000 and greater than 1000000, but still decided to do it without considering the upper and lower limits of a+b , the idea is to first use the for loop to divide by 10 to determine the total number of digits of a+b, and then set two numbers, one for dividing and one for remainder.
 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 } 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324946407&siteId=291194637