国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++實現大數乘法算法代碼

2020-01-26 15:09:39
字體:
來源:轉載
供稿:網友

C++實現大數乘法算法代碼

復制代碼 代碼如下:

//大數乘法算法
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
    string num1,num2;
    cin >> num1 >> num2;
    //cout << num1.size() << " " << num2.size() << endl;
    const char* n1;
    const char* n2;
    if (num1.size() < num2.size())
    {
        n1 = num2.c_str();
        n2 = num1.c_str();
    }
    else
    {
        n1 = num1.c_str();
        n2 = num2.c_str();
    }
    char* n = new char[strlen(n1)+strlen(n2)+1];
    for (unsigned int i = 0; i < strlen(n1)+strlen(n2); i++)
        n[i] = '0';
    n[strlen(n1)+strlen(n2)]='/0';
    //cout << strlen(n) << endl;
    int count = 0,flag = 0;
    for (int i = strlen(n1)-1; i >= 0; i--)
    {
        flag++;
        int x1 = n1[i]-'0';
        //cout << "n1["<< i << "]為:" << x1 << endl;
        char carry = '0';
        for (int j = strlen(n2)-1; j >= 0; j--)
        {
            int x2 = n2[j]-'0';
            //cout << "n2["<< j << "]為:" << x2 << endl;
            //cout << "當前位未改變前值為: " << n[count] << endl;
            int sum = x1*x2 + (carry-'0') + n[count]-'0';
            //cout << "sum is " << sum << endl;
            n[count++] = (sum % 10)+'0';
            carry = (sum / 10)+'0';
            //cout << "當前位的值為: " << n[count-1] << endl;
            //cout << "carry的值為:" << carry << endl;
        }
        if (carry != '0')
        {
            n[count] = carry;
            count = flag;
            //cout << "當前位的值為: " << n[count] << endl;
        }
        else
            count = flag;
    }
    for (int i = strlen(n)-1; i >= 0; i--)
    {
        if ((i == strlen(n)-1)&&(n[i] == '0'))
            continue;
        cout << n[i];
    }
    cout << endl;
    delete[]n;
    system("pause");
    return 0;
}

以上就是本文所述的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南溪县| 黄冈市| 云南省| 宣威市| 昆山市| 宁乡县| 滦平县| 延津县| 炉霍县| 灵川县| 宝应县| 金堂县| 太康县| 博乐市| 英超| 台南市| 哈巴河县| 平度市| 金坛市| 苍溪县| 大荔县| 九江县| 金川县| 鄂尔多斯市| 静安区| 应城市| 兴海县| 海盐县| 潍坊市| 鹤山市| 靖西县| 中山市| 临高县| 南安市| 桐城市| 怀柔区| 崇仁县| 同德县| 日喀则市| 宜丰县| 宝兴县|