另一种方法才40多行就对了,为啥下面的代码就错了呢??蒟蒻求助

P1009 [NOIP1998 普及组] 阶乘之和

ouiostream @ 2023-10-25 17:14:20

#include<bits/stdc++.h>
#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]);
    }
};
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 ans(0),fac(1);
    int m;
    cin>>m;
    for(int i=1;i<=m;i++){
        fac=fac*i;
        ans=ans+fac;
    }
    ans.print();
}

这串代码是错的,为啥错呢,大佬求助


by AK_CSPS @ 2023-10-25 17:37:46

这段代码的错误在于 Bigint::flatten() 方法的实现。该方法应该将高位进位到低位,但是实现中的代码有误,导致结果不正确。正确的实现方式应该是将第 10 行的 a[i]%10 改为 a[i]/10,如下所示:

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

by laozhang_123 @ 2023-10-29 12:51:30

i是int型,但你的operator* 中b是Bigint型

可参考下面的代码

#include<bits/stdc++.h>
#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]);
    }
}; 
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,int b){
    Bigint c;
    int len=a.len;
    for(int i=1;i<=len;i++)
        c[i]=a[i]*b;
    c.flatten(len+11);
    return c;
}
int main(){
    Bigint ans(0),fac(1);
    int m;
    cin>>m;
    for(int i=1;i<=m;i++){
        fac=fac*i;
        ans=ans+fac;
    }
    ans.print();
    return 0;
} 

by ouiostream @ 2023-11-06 12:27:18

@laozhang_123 @jiang1008 谢谢


|