1001. A+B Format (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
在这道题目中,需要注意的就是输入-1000和1时,输出应该是-999,而不是-,999,同理,-1000000和1也是一样。
输出的时候需要一个一个输出,这个时候可以把整型转换成字符串,这个可以用stringstream完成(头文件sstream)
具体代码如下 :
#include<iostream>
#include<cstring>
#include<sstream>
using namespace std;
int main(){
int a,b,sum;
string s;
while(cin>>a>>b){
stringstream ss;
sum=a+b;
if(sum<0){cout<<"-";sum=-sum;}
ss<<sum;
s=ss.str();
int len=s.length();
for(int i=0;i<len;i++){
if(len!=4||s[0]!='-')
if((len-i)%3==0&&i>0) cout<<",";
cout<<s[i];
}
cout<<endl;
}
}
!!!注意对负数的处理