【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

程序设计:
  1.先对和 sum 求绝对值,定义一个布尔型变量记录sum的正负
  2.对 sum 进行条件判断
    1)sum <1000 ,判断正负,直接打印
    2)1000<= sum <1000000 ,判断正负,打印一个逗号
    3)sum >=1000000 ,判断正负,打印两个逗号
  3.对于正负的判断使用三目运算符
//两种均可 
cout<<(flag?"-":"\0")<<sum;  
cout<<(flag?"-":"")<<sum;
    若非负,则打印空字符"\0"(不是空格),若为负,打印"-"
    **注意:若程序为 flag?'-':'\0' ,则'\0'打印出的为空格,所以要写出"-"和"\0"
  4.关于 '\0' 和 "\0"
    \0 为结束字符,对应的 ASCII值为0,在ASCII中占一个字节,所以打印 '\0'会显示空格
    在 \0 后面的字符全为空,所以仅包含 \0 的字符串为空串,即 "\0" 为空字符串,和 "" 效果一样
    在使用 strlen() 函数求字符串的长度时,结束字符'\0'不会被计算在内;当使用 sizeof() 函数求字符串占用的内存空间时,结束字符'\0' 被计算在内
  5.注意在打印时,为0的位置上要补0

C++ 代码如下:
 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 }

猜你喜欢

转载自www.cnblogs.com/pgzhang/p/8961035.html
今日推荐