1001 A+B Format (20)(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.
计算整数和,并输出有分隔符的格式,
---5个测试点未通过
#include<iostream>
#include<vector>
#include<cmath>
#include<cstdio>
using namespace std;
void add(int arg0,int arg1){
int t=arg0+arg1;
if(t==0) {
cout<<0;
return;
}
vector<int> a;
while((t/1000>0)||(t%1000!=0)){
int y=t%1000;
a.push_back(y);
t=t/1000;
}
int l=a.size();
if(l==1){
cout<<a[0];
return;
}
else if(l>1){
l--;
cout<<a[l]<<",";
while(l>1){
l--;
cout<<abs(a[l])<<",";
}
cout<<abs(a[0]);
}
else {
return;
}
}
int main(){
int c1,c2;
scanf("%d%d",&c1,&c2);
add(c1,c2);
return 0;
}
------修改通过
①先判断t正负,然后t=-t
②修改cout为printf
#include<iostream>
#include<vector>
#include<cmath>
#include<cstdio>
using namespace std;
void add(int arg0,int arg1){
int t=arg0+arg1;
if(t==0) {
cout<<0<<endl;
return;
}
if(t<0){
cout<<"-";
t=-t;
}
vector<int> a;
while((t/1000>0)||(t%1000!=0)){
int y=t%1000;
a.push_back(y);
t=t/1000;
}
int l=a.size();
if(l==1){
cout<<a[0];
return;
}
else{
l--;
cout<<a[l]<<",";
while(l>1){
l--;
printf("%03d,",a[l]); //在我的编译器输出有误,应去掉ABS()
}
printf("%03d",a[0]);
}
}
int main(){
int c1,c2;
scanf("%d%d",&c1,&c2);
add(c1,c2);
return 0;
}
一个简洁的版本:
#include<iostream>
using namespace std;
int main(){
int a,b,c,i;
cin>>a>>b;
c=a+b;
string s=to_string(c);
for(i=s.size();(c>0?i>3:i>4);i-=3)
s.insert(i-3,",");
cout<<s<<endl;
return 0;
}