高精度運算(大數加法)
阿新 • • 發佈:2019-02-07
在計算過大的數字時,我們可以使用字串進行儲存,再模擬計算過程,結果也用字串儲存,最後輸出這個字串
加法:
#include<iostream> #include<cstdio> #include<cstring> #include<string> using namespace std; int main() { string a, b; cin >> a >> b; int l1 = a.size(); int l2 = b.size(); if(l1 < l2) { string temp = a; a = b; b = temp; } l1--, l2--; int G = 0; while(l2 >= 0) { int S = a[l1] - '0' + b[l2] - '0'+ G; G = S/10; S = S % 10; a[l1] = S + '0'; l1--, l2--; } while(l1 >= 0) { int S = a[l1] - '0' + G; G = S/10; S = S % 10; a[l1] = S + '0'; l1--, l2--; } if(G != 0) a = '1' + a; cout << a << endl; }
上面那個雖然能計算,但是有紕漏,再來一個修改的
#include<iostream> #include<cstdio> #include<cstring> #include<string> using namespace std; int main() { string a, b; cin >> a >> b; cout << a << " + " << b << " = "; int l1 = a.size(); int l2 = b.size(); if(l1 < l2) { string temp = a; int t = l1; a = b; l1 = l2; b = temp; l2 = t; } l1--, l2--; int G = 0; while(l2 >= 0) { int S = a[l1] - '0' + b[l2] - '0'+ G; G = S/10; S = S % 10; a[l1] = S + '0'; l1--, l2--; } while(l1 >= 0) { int S = a[l1] - '0' + G; G = S/10; S = S % 10; a[l1] = S + '0'; l1--, l2--; }+ if(G != 0) a = '1' + a; cout << a << endl; return 0; }