为啥用string是0分,求解释

P1009 [NOIP1998 普及组] 阶乘之和

LOVEZMD @ 2022-12-20 13:10:13

#include<iostream>
#include<string>
#include<algorithm> 
using namespace std;
string add(string numa,string numb){
    string str;
    int len = max(numa.length(),numb.length()),last = 0;
    while(numa.length()<len) numa = "0"+numa;
    while(numb.length()<len) numb = "0"+numb;
    for(int i=len-1;i>=0;i--){
        int p = numa[i]+numb[i]-2*'0'+last;
        if(p>=10){
            p%=10;
            last = 1;
        }
        else last = 0;
        str=char(p+'0')+str;
    }
    return str;
}
string mul(string numa,string numb){
    string ans="0",str[numb.length()];
    for(int i=numb.length()-1;i>=0;i--){
        int last = 0,a;
        for(int t=numa.length()-1;t>=0;t--){
            int p = (numb[i]-'0')*(numa[t]-'0')+last;
            if(p>=10){
                last = p/10;
                p%=10;
                if(t==0){
                    a = last;
                }
            }
            else last = 0;
            str[i]=char(p+'0')+str[i];
        }
        str[i].append(numb.length()-1-i,'0');
        if(a!=0){
            str[i]=char(a+'0')+str[i];
        }
        ans=add(ans,str[i]);
    }
    return ans;
}
int main(){
    int n;
    cin>>n;
    string num[n];
    string S = "0";
    for(int i=0;i<n;i++){
        num[i]="1";
        for(int t=2;t<=1+i;t++){
            num[i]=mul(num[i],to_string(t));
        }
        S=add(S,num[i]);
    }
    cout<<S;
    return 0;
}

by HeiGi @ 2022-12-20 14:35:41

应该是越界了


|