PAT A1001

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值