换了个写法……然后WA

P1303 A*B Problem

Star_Sky_ @ 2023-12-21 17:38:21

#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
#include <cmath>

using namespace std;

class num
{
    public:
        int sum[5000] , len; 

        num (string in = "0")
        {
            memset(sum , 0 , sizeof(sum));

            len = in.size();

            for (int i = len - 1 ; i >= 0 ; i--)
            {
                sum[i] = in[len - i - 1] - 48;
            }
        }

        void print()
        {   
            for (int i = len - 1; i >= 0 ; i--)
            {
                //printf("%d" , sum[i]);
                putchar(sum[i]+48);
            } 
        }

        void save()
        {
            for (int i = 0 ; i <= len ; i++)
            {
                sum[i+1] += sum[i]/10;
                sum[i] %= 10;
            }

            while (!sum[len-1])
            {
                len--;
            }

            if (len == 0) len++;
        }

        void get()
        {
            string tmp;
            cin >> tmp;

            memset(sum , 0 , sizeof(sum));

            len = tmp.size();

            for (int i = len - 1 ; i >= 0 ; i--)
            {
                sum[i] = tmp[len - i - 1] - 48;
            }
        }

        int &operator [] (int i)
        {
            return sum[i];
        }
};

num operator * (num a , num b)
{
    num ou;

    ou.len = a.len + b.len;

    for (int i = a.len-1 ; i >= 0 ; i--)
    {
        for (int j = b.len-1 ; j >= 0 ; j--)
        {
            ou[i+j] += a[i]*b[i];
        }
    }

    ou.save();

    return ou;
}

int main()
{
    num a , b , c;

    a.get();b.get();

    c = a * b;
    c.print();

    return 0;
}

发现好像是计算出了问题:比如10*10 = 110.但没查出问题希望大佬救救!!!


by Hukaidi8566 @ 2023-12-22 13:33:53

有两个问题:

一、当输入的是 “0 1” 时,这段代码什么也不会输出,你可以在48行后面加上

printf("len=%d\n");

看看 len 到底是几。

一般我们会把第43行改成

while (!sum[len-1]&&len>1)

二、82行你再看一看


by Star_Sky_ @ 2023-12-25 12:55:26

@Hukaidi8566 谢谢


by Star_Sky_ @ 2023-12-25 14:12:26

@Hukaidi8566 我改了一下,应该是

ou[ou.len-i-j-1] += a[i]*b[i];

但是依然不对,想再问问。

甚至10*10=1100


by Hukaidi8566 @ 2023-12-25 14:22:27

@2023libingxuan

ou[i+j] += a[i]*b[i];

改为

ou[i+j] += a[i]*b[j];

by Star_Sky_ @ 2023-12-25 16:36:25

@Hukaidi8566 才发现自己犯了这种低级错误……


|