大数乘法

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

void main()
{
    string num1;
    string num2;
    cin >> num1;
    cin >> num2;

    int temp[200][200] = {0};//用于保存每位相乘的结果
        /*154 1234

        0   0   4   8  12  16
        0   5  10  15  20   0
        1   2   3   4   0   0
        1   7  17  27  32  16*/

    for (int i = num1.length() - 1; i >= 0; i--)//从最后一位开始与另一个数相乘
    {
        for (int j = 0; j < num2.length(); j++)
        {
            temp[num1.length()-1-i][j+i] = (num1[i] - 48)*(num2[j] - 48);//(举特例)如果num1是三位 则后面向前依次进位两次 所以为前面为长度2个0 所以要加上i(n-1)
        }
    }

    //输出两个数相乘后的结果          两个数相乘 没进位之前的列数为len1+len2-1
    for (int i = 0; i < num1.length(); i++)
    {
        for (int j = 0; j < num2.length() + num1.length()-1; j++)
        {
            cout << setw(4) << temp[i][j];
        }
        cout << endl;
    }

    //求每一列的和保存在res中
    int res[100] = {0};
    for (int i = 0; i < num2.length() + num1.length() - 1; i++)
    {
        for (int j = 0; j < num1.length(); j++)
        {
            res[i] += temp[j][i];
        }
    }

    //输出res
    for (int i = 0; i < num2.length() + num1.length() - 1; i++)
    {
        cout << setw(4) << res[i];
    }
    cout << endl;

    //对res进行进位 一直到第1位 0位不用进位
    for (int i = num2.length() + num1.length() - 2; i>0; i--)
    {
        res[i - 1] += res[i] / 10;
        res[i] %= 10;
    }

    cout << "\n\n\n" <<  num1 << "  *  " << num2 << "   =   ";
    for (int i = 0; i < num2.length() + num1.length() - 1; i++)
    {
        cout << res[i];
    }
    cout << endl;
    system("pause");
}

 

posted @ 2016-01-15 21:15  喵小喵~  阅读(158)  评论(0编辑  收藏  举报