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++ 代码如下:
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,sum;
bool flag=false;
cin>>a>>b;
sum=a+b;
if(sum<){
sum=abs(sum);
flag=true;
}
if(sum<) cout<<(flag?"-":"")<<sum;
else if(<=sum&&sum<)
cout<<(flag?"-":"")<<(sum/)<<','<<setw()<<setfill('')<<(sum%);
else {
cout<<(flag?"-":"")<<(sum/);
cout<<","<<setw()<<setfill('')<<(sum%/);
cout<<','<<setw()<<setfill('')<<(sum%%);
}
system("pause");
return ;
}