【PAT】1001. A+B Format (20)

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

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 

Programming:
  1. First find the absolute value of sum and sum, define a Boolean variable to record the positive and negative
  of sum 2. Conditionally judge
    sum 1) sum <1000, judge the positive or negative, print directly
    2) 1000<= sum <1000000 , judge positive and negative, print a comma
    3) sum >=1000000 , judge positive and negative, print two commas
  3. Use ternary operator for positive and negative judgment
// Both are available
cout<<(flag?"-":"\0")<<sum;  
cout<<(flag?"-":"")<<sum;
    If it is not negative, print the null character "\0" (not a space), if it is negative, print "-" 
    **Note: If the program is flag?'-':'\0', then '\0' prints out is a space, so write "-" and "\0"
  4. Regarding '\0' and "\0"
    \0 is the end character, the corresponding ASCII value is 0, which occupies one byte in ASCII, so print '\0' will display a space
    . The characters after \0 are all empty, so the string containing only \0 is an empty string, that is, "\0" is an empty string, and the same effect as "" is
    using the strlen() function When calculating the length of the string, the end character '\0' will not be counted; when using the sizeof() function to calculate the memory space occupied by the string, the end character '\0' will be counted.
  5. Note that when printing When it is 0, the position of 0 should be filled with 0. The

C++ code is as follows:
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main() {
 4     int a,b,sum;
 5     bool flag=false;
 6     cin>>a>>b;
 7     sum=a+b;
 8     if(sum<0){
 9         sum=abs(sum);
10         flag=true;
11     }
12     if(sum<1000) cout<<(flag?"-":"")<<sum;
13     else if(1000<=sum&&sum<1000000)
14         cout<<(flag?"-":"")<<(sum/1000)<<','<<setw(3)<<setfill('0')<<(sum%1000);        
15     else {
16         cout<<(flag?"-":"")<<(sum/1000000);
17         cout<<","<<setw(3)<<setfill('0')<<(sum%1000000/1000);
18         cout<<','<<setw(3)<<setfill('0')<<(sum%1000000%1000);
19     }    
20     system("pause");    
21     return 0;
22 }

Guess you like

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