大数相乘——模拟乘法的运算规则

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>

int main()
{
    void add(int a[], int length1, int b[], int length2);
    char str1[255], str2[255];
    int num1[255] = { 0 }, num2[255] = { 0 };
    int product[255] = { 0 }, temp[255] = {0};//temp用于存放乘法的中间值。比如计算123*3时,temp依次为369,246,123.
    int length1, length2, length;
    int i, j;

    gets(str1);
    gets(str2);
    length1 = strlen(str1);
    length2 = strlen(str2);
    length = length1 > length2 ? length1 : length2;

    //将两个数存入到num[]中
    for (i = 0; i <= length1 - 1; i++)
    {
        num1[i] = str1[i] - '0';
    }

    for (i = 0; i <= length2 - 1; i++)
    {
        num2[i] = str2[i] - '0';
    }

    for (i = length2 - 1; i >= 0; i--)
    {
        for (j = length1 - 1; j >= 0; j--)
        {
            temp[j] = temp[j] + num2[i] * num1[j];
            if ((temp[j] >= 10) && (j != 0))
            {
                temp[j - 1] = temp[j] / 10;//表示向前的进位
                temp[j] = temp[j] % 10;
            }
        }
        //计算123*3时,temp值369,246,123需要转换为369,2460,12300之后,再相加。
        //i=length2-1时,temp的长度为length1;
        //i=length2-2时,temp的长度为需转为length1+1;
        //所以temp的长度为length1 + length2 - i - 1。
        add(product, length1 + length2 - i - 2,temp, length1 + length2 - i - 1);
        memset(temp, 0, sizeof(int) * 255);
    }

    for (i=0; i < length1 + length2 - 1; i++)
    {
        printf("%d", product[i]);
    }

    return 0;
}

//函数功能:将大数a和大数b相加,结果存放于a中。length1和length2分别为大数a和大数b的长度。
void add(int a[], int length1,int b[], int length2)
{
    int i, j;
    int num1[255] = { 0 }, num2[255] = { 0 };
    int length;

    length = length1>length2 ? length1 : length2;
    for (i = length - 1, j = length1 - 1; j >= 0; i--, j--)
    {
        num1[i] = a[j];
    }
    for (i = length - 1, j = length2 - 1; j >= 0; i--, j--)
    {
        num2[i] = b[j];
    }

    for (i = length-1; i >= 0; i--)
    {
        num1[i] = num1[i] + num2[i];
        if ((num1[i] >= 10) && (i != 0))
        {
            //此处不能使用num1[i - 1] += 1.因为进位不一定为1.
            //比如999*99时,中间值为['0','89','9','1']和['89','9','1','0']。89和9相加后,进位为9.
            num1[i - 1] += num1[i] / 10;//表示进位。
            num1[i] = num1[i] % 10;
        }
    }

    for (i = 0; i < length; i++)
    {
        a[i] = num1[i];
    }
}

转载于:https://www.cnblogs.com/Camilo/p/3834442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值