C言語で高精度加算を実現
本編では高精度加算の計算をしていますが、これからは高精度乗算の計算を書きます。
一、高精度演算の概念
高精度演算とは、基本データタイプが表す範囲を完全に超えた演算のことです。
大きな数を求めるなら、新しいデータタイプを作成します。
二、データタイプの選択
私が選んだのはint型の配列です。これは計算と理解に便利です。
三、コード
その中のaとbはランダムで数えて、価値を与えます。
結果はスクリーンショットがあり、検証されていませんでした。
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。
一、高精度演算の概念
高精度演算とは、基本データタイプが表す範囲を完全に超えた演算のことです。
大きな数を求めるなら、新しいデータタイプを作成します。
二、データタイプの選択
私が選んだのは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);
}
四、結果結果はスクリーンショットがあり、検証されていませんでした。
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。