本篇爲高精度加法的計算,接下來我還會去寫高精度乘法的計算
一、高精度運算的概念
高精度運算其實就是參與運算的數完全超出基本數據類型所能表示的範圍的運算(例如int型範圍就是 - 2147483648 ~+ 2147483647)
所以如果想求較大數的話就要創建新的數據類型
二、數據類型的選取
我選擇的是int型數組,這樣比較便於計算和理解
三、代碼
其中a和b我是通過隨機數來賦值
//author summer_awn
//date 2017/6/20
#include<iostream>
#include<time.h>
#define lenth_a 200
#define lenth_b 200
using namespace std;
//計算a+b
void main() {
srand((unsigned)time(NULL));
int * a = new int[lenth_a];//數組a ******
for (int i = 0; i < lenth_a; ++i) {
a[i] = rand() % 10;
}
cout << "a=";
for (int i = lenth_a - 1; i >= 0; --i) {//輸出a
cout << a[i];
}
cout << endl;
cout << endl;
int * b = new int[lenth_b];//數組b ******
for (int i = 0; i < lenth_a; ++i) {
b[i] = rand() % 10;
}
cout << "b=";
for (int i = lenth_b - 1; i >= 0; --i) {//輸出b
cout << b[i];
}
cout << endl;
cout << endl;
int lenth_result;//結果的長度en
if (lenth_a > lenth_b) lenth_result = lenth_a + 1;
else lenth_result = lenth_b + 1;//通過一個判斷來確定結果的長度
int * a2 = new int[lenth_result];//a2***********
int * b2 = new int[lenth_result];//b2***********
memcpy(a2, a, sizeof(int)*lenth_a);//
memset(a2 + lenth_a, 0, sizeof(int)*(lenth_result - lenth_a));
memcpy(b2, b, sizeof(int)*lenth_b);
memset(b2 + lenth_b, 0, sizeof(int)*(lenth_result - lenth_b));
delete(a);
delete(b);
int * result = new int[lenth_result];//result*********
result[0] = a2[0] + b2[0];
for (int i = 1; i < lenth_result - 1; ++i) {
result[i] = a2[i] + b2[i] + result[i - 1] / 10;
result[i - 1] = result[i - 1] % 10;
}
result[lenth_result - 1] = result[lenth_result - 2] / 10;
result[lenth_result - 2] = result[lenth_result - 2] % 10;
delete(a2);
delete(b2);
cout << "結果=";
for (int i = lenth_result - 1; i >= 0; --i) {
cout << result[i];
}
cout << endl;
system("pause");
delete(result);
}
四、結果
結果有截圖,未驗證(因爲懶)
總結一下,覺得自己的方法還是挺爛的,有好的建議歡迎留言