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 Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6
≤a,b≤10^6,The numbers are separated by a space.
Output Specification:
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
题目的意思是对两个整数求和并格式化
毕竟是刚开始,题并不算难,但对我这种编程小白来说还是遇到许多意向不到的问题…
下面是我凭“一己之力”写出的代码
#include
#include
using namespace std;
string sum(int a,int b){
int sum=a+b;
string s=to_string(sum);
return s;
}
int main(){
int a,b,n,i;
cin>>a>>b;
string s=sum(a,b);
n=s.length();
while(!(n%3==0&&n/3==1)){
if(n%3==0){
cout<<s.substr(0,3)<<",";
s=s.substr(0,3);
n=n-3;
}else{
i=n%3;
if(i==1){
cout<<s.substr(0,1)<<",";
s=s.substr(0,1);
n=n-i;
}else if(i==2){
cout<<s.substr(0,2)<<",";
s=s.substr(0,2);
n=n-i;
}
}
}
if(n%3==0&&n/3==1){
cout<<s<<endl;
}
}
首先,在写代码的过程中因为对C++的string使用不熟练,在这个方面犯了很多白痴的错误,还需要多看string的函数使用,学校的ACM大佬说在PAT甲级中的string用的地方还挺多的。
然后,在代码通过编译之后,出现许多的答案错误,需要对代码进行修改和优化。
在过程中遗漏了“-”,在转化为字符串时,“-”也进入了字符长度的统计,而且在 s=s.substr(0,1);的表述中也存在很大问题,应该把s赋值为剩余的部分,而不是已经输出的部分。
代码修改如下:
#include
#include
#include
using namespace std;
int main(){
int a,b,n,i,sum,sum0;
cin>>a>>b;
sum=a+b;
sum0=abs(sum);
string s=to_string(sum0);
n=s.length();
if(sum<0){
cout<<"-";
}else if(sum==0){
cout<<0<<endl;
}
while(!(n%3==0&&n/3==1)){
if(n%3==0){
cout<<s.substr(0,3)<<",";
n=n-3;
s=s.substr(3,n);
}else{
i=n%3;
if(i==1){
cout<<s.substr(0,1)<<",";
n=n-1;
s=s.substr(1,n);
}else if(i==2){
cout<<s.substr(0,2)<<",";
n=n-2;
s=s.substr(2,n);
}
}
}
if(n%3==0&&n/3==1){
cout<<s<<endl;
}
}
#include
#include
#include
using namespace std;
int main(){
int a,b,n,i,sum,sum0;
cin>>a>>b;
sum=a+b;
sum0=abs(sum);
string s=to_string(sum0);
n=s.length();
if(sum<0){
cout<<"-";
}else if(sum==0){
cout<<0<<endl;
}
while(n>3){
if(n%3==0){
cout<<s.substr(0,3)<<",";
n=n-3;
s=s.substr(3,n);
}else{
i=n%3;
if(i==1){
cout<<s.substr(0,1)<<",";
n=n-1;
s=s.substr(1,n);
}else if(i==2){
cout<<s.substr(0,2)<<",";
n=n-2;
s=s.substr(2,n);
}
}
}
if(n==3||n==2||n==1){
cout<<s<<endl;
}
}
看了其他博主的解法,发现大家的解法都很简单易懂pat甲级1001
#include
using namespace std;
int main(){
int a,b;
cin>>a>>b;
if(a+b<0)
cout<<"-";
string s=to_string(abs(a+b));
int i=s.size()%3==0?3:s.size()%3;
cout<<s.substr(0,i);
for(;i<s.size();i+=3)
cout<<","<<s.substr(i,3);
return 0;
}