日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C++?高精度乘法運(yùn)算的實(shí)現(xiàn)_C 語言

作者:CairBin ? 更新時(shí)間: 2023-03-03 編程語言

思想

首先確定乘積的位數(shù)。

假設(shè)兩個(gè)非負(fù)整數(shù)a和b,n1為a的長(zhǎng)度(位數(shù)),n2為b的位數(shù),記n為c=a*b的位數(shù),則有:

計(jì)算兩個(gè)乘數(shù)每位數(shù)字的乘積,其中a[i]乘b[j]累加到c[i+j]上去

在最后對(duì)累加結(jié)果數(shù)組c作一次性進(jìn)位(判斷是否大于等于10)

代碼

知道上述原理,很容易就寫出代碼

#include <iostream>
#include <string>
#include <algorithm>
#include <string.h>

using namespace std;
int main()
{
? ? //輸入時(shí)處理,包含置0、逆置、轉(zhuǎn)換成真實(shí)數(shù)字等步驟
? ? string s;
? ? cin >> s;
? ? int n1 = s.length();?? ?//長(zhǎng)度
? ? char str1[10];
? ? memset(str1, 0, sizeof(str1));
? ? for (int i = 0; i < n1;i++)
? ? ? ? str1[i] = s[n1 - i - 1]-'0';
? ??
? ? string s2;
? ? cin >> s2;
? ? int n2 = s2.length();
? ? char str2[10];
? ? memset(str2, 0, sizeof(str2));
? ? for (int i = 0; i < n2;i++)
? ? ? ? str2[i] = s2[n2 - i - 1]-'0';


? ? char res[20];
? ? memset(res, 0, sizeof(res));

? ? //核心代碼
? ? int i, j;
? ? for (i = 0; i < n1;i++)
? ? ? ? for (j = 0; j < n2;j++)
? ? ? ? ? ? res[i + j] += str1[i] * str2[j];

? ? for (i = 0; i < n1 + n2;i++)
? ? {
? ? ? ? if(res[i]>=10)
? ? ? ? {
? ? ? ? ? ? res[i + 1] += res[i] / 10;
? ? ? ? ? ? res[i] %= 10;
? ? ? ? }

? ? }

? ? //從不為0的那一位開始輸出(刪除前導(dǎo)0),如果全部為0,則輸出0
? ? int k;
? ? for (k = n1 + n2 - 1; !res[k]&&k>0; k--)
? ? ? ? ; ? //注意這個(gè)分號(hào)

? ? for (int i = k; i >= 0; i--)
? ? ? ? cout << int(res[i]);
? ? cout << endl;


? ? return 0;
}

原文鏈接:https://blog.csdn.net/qq_42759112/article/details/128635218

欄目分類
最近更新