为什么编写出来的scanf的函数有问题,请大佬们看一看

P1001 A+B Problem

wkl20110514 @ 2022-12-08 13:41:22

为什么编写出来的scanf的函数有问题,请大佬们看一看

struct bigint{
    int len,a[maxn];
    bigint(int x=0){
        memset(a,0,sizeof(a));
        for(len=1;x;len++)
            a[len]=x%10,x/=10;
        len--;
    }
    int &operator[](int i){
        return a[i];
    }
    void flatten(int L){
        len=L;
        for(int i=1;i<=len;i++)
            a[i+1]+=a[i]/10,a[i]%=10;
        for(;!a[len];)
            len--;
    }
    void print(){
        for(int i=max(len,1);i>=1;i--)
            printf("%d",a[i]);
    }
    void scanf(){//这里有问题
        string zf;
        cin>>zf;
        int len_zf=zf.length();
        for(int i=len_zf;i>=1;i--)
            a[i]=zf[i]-'0';
    }
};
bigint operator+(bigint a,bigint b){
    bigint c;
    int len=max(a.len,b.len);
    for(int i=1;i<=len;i++)
        c[i]+=a[i]+b[i];
    c.flatten(len+1);
    return c;
}
bigint operator*(bigint a,bigint b){
    bigint c;
    int len=a.len;
    for(int i=1;i<=len;i++)
        c[i]=a[i]*b[i];
    c.flatten(len+11);
    return c;
}

我的代码主要是用的《深入浅出》里的,想自己加一个输入


by wkl20110514 @ 2022-12-08 14:49:15

还是不行呢,可以再帮我看看么

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#define maxn 100
using namespace std;
struct bigint{
    int len,a[maxn];
    bigint(int x=0){
        memset(a,0,sizeof(a));
        for(len=1;x;len++)
            a[len]=x%10,x/=10;
        len--;
    }
    int &operator[](int i){
        return a[i];
    }
    void flatten(int L){
        len=L;
        for(int i=1;i<=len;i++)
            a[i+1]+=a[i]/10,a[i]%=10;
        for(;!a[len];)
            len--;
    }
    void print(){
        for(int i=max(len,1);i>=1;i--)
            printf("%d",a[i]);
    }
    void read(){
        string zf;
        cin>>zf;
        len=zf.length();
        for(int i=len-1;i>=0;i--)
            a[i]=zf[i]-'0';
    }
};
bigint operator+(bigint a,bigint b){
    bigint c;
    int len=max(a.len,b.len);
    for(int i=1;i<=len;i++)
        c[i]+=a[i]+b[i];
    c.flatten(len+1);
    return c;
}
bigint operator*(bigint a,bigint b){
    bigint c;
    int len=a.len;
    for(int i=1;i<=len;i++)
        c[i]=a[i]*b[i];
    c.flatten(len+11);
    return c;
}
int main(){
    bigint a=0,b=0;
    a.read();
    b.read();
    a=a+444;
    (a+b).print();
    return 0;
}

by NormanWang @ 2022-12-08 15:01:16

@wkl20110514

for(int i=0;i<len;i++)
    a[len-i]=zf[i]-'0';

by wkl20110514 @ 2022-12-08 16:49:22

可以了,谢谢啦


by cheng110527 @ 2023-02-14 21:14:35

#include <iostream>

using namespace std;

int main(){
    int a,b;
    cin >> a >> b;
    cout << a + b;
    return 0;
}

正解(写那么复杂有必要吗)


上一页 |