本篇为高精度加法的计算,接下来我还会去写高精度乘法的计算。
一、高精度运算的概念
高精度运算其实就是参与运算的数完全超出基本数据类型所能表示的范围的运算(例如int型范围就是 - 2147483648 ~+ 2147483647)
所以如果想求较大数的话就要创建新的数据类型
二、数据类型的选取
我选择的是int型数组,这样比较便于计算和理解
三、代码
其中a和b我是通过随机数来赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
//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);
}
|
四、结果
结果有截图,未验证(因为懒)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/summer_awn/article/details/73478496