悬2关高精乘法板子红题求助

P1303 A*B Problem

zhangmingsheng3521 @ 2023-08-24 22:14:00

rt.代码只要碰到要进位的情况就会炸.

代码如下(AC给关,但是大框架不能改,有注释,相对友好)

#include"bits/stdc++.h" 
using namespace std;
int a[2002],b[2002],c[4004];//a,b乘数c积
int main()
{
    int mark;
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));
    string s;
    cin>>s;//读入
    int n1=s.size();
    for (int i=0;i<n1;i++)
    {
        a[i]=int(s[i])-48;
    }
    cin>>s; 
    int n2=s.size();
    for (int i=0;i<n2;i++)
    {
        b[i]=int(s[i])-48;
    }
    for (int i=0;i<n1;i++)
    {
        for (int j=0;j<n2;j++)
        {
            c[i+j]+=a[i]*b[j];//乘法
            c[i+j+1]+=c[i+j]/10;//进位
            c[i+j]=c[i+j]%10;
        }
    }
    for (int i=4003;i>=1;i--)//定位首个非0
    {
        if (c[i]!=0)
        {
            mark=i;
            break;
        }
    }
    for (int i=0;i<=mark;i++)//输出
    {
        printf("%d",c[i]);
    } 
    return 0;
}

by gfgoodluck @ 2023-08-24 22:17:19

但是不是最好倒着做吗/yiw


by gfgoodluck @ 2023-08-24 22:17:56

你从最高位开始算是不是错的啊


by gfgoodluck @ 2023-08-24 22:18:03

@zhangmingsheng3521


by Infinity_Fantasy @ 2023-08-24 22:21:17

是的,没有倒叙存储,114 * 10 直接给你搞掉了


by Infinity_Fantasy @ 2023-08-24 22:21:34

倒序


by Infinity_Fantasy @ 2023-08-24 22:22:35

还有你数组似乎开小了,c要开到4000000


by gfgoodluck @ 2023-08-24 22:23:13

@AK_CCF ?


by Infinity_Fantasy @ 2023-08-24 22:24:28

没问题的,ab都是2000位的,乘起来是4000000


by gfgoodluck @ 2023-08-24 22:25:05


by gfgoodluck @ 2023-08-24 22:25:24

@AK_CCF


| 下一页