改到最后都快和书上一模一样了,为什么还是输出不了?

P1009 [NOIP1998 普及组] 阶乘之和

xiuman @ 2024-01-21 20:31:50

#include<bits/stdc++.h>
using namespace std;
#define maxn 100
struct bigint{
    int len,a[maxn];
    bigint(int x=0){
        memset(a,0,sizeof(a));
        for(int 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]==0;)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),num(1);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        num=num*i;
        ans=ans+num;
    }
    ans.print();
}

by Auto_Accepted @ 2024-01-21 20:43:31

@xiuman 你尝试一下输出最后的 anslen,可能是 len 小于 1 了。(求关注)


by Auto_Accepted @ 2024-01-21 20:44:59

@xiuman 偶不对,运行时错误了,检查一下数组下标越界


by NitsugaoO @ 2024-01-21 21:01:27

@xiuman 第8行for循环括号里面把int去掉,不然外面的len只是单纯--了 然后就越界了。


by xiuman @ 2024-01-22 18:26:50

thank you,过了过了


|