一、高精度数
用一个数组表示一个数字,将这个数字拆开成一位一位或四位四位存储到一个数组中。
二、基本方法
一个数组首先存储数字的位数,再将数字倒序存储,即先存个位再到十位,以此类推。
#include <iostream>
#include <cstring>
using namespace std;
//高精度数的读入和存储:将字符串转为数字并进行存储
int a[1015];//存储每个字符对应的数字
void string2int(char s[]) {
a[0] = strlen(s);
for (int i = a[0], j = 0; i >= 1; i--, j++) {
a[i] = s[j] - '0'; //倒序存储数字
}
for (int i = 1; i <= a[0]; i++) {
cout << a[i];
}
cout << endl;
return ;
}
int main() {
char s[1010];
cin >> s;
string2int(s);
return 0;
}
三、输出
忽略数组中后面所有的无效0,即从数组中最右侧的非0位开始依次输出数字。
i=1000(可以直接设数据位数上限)
while(a[i]==0)i--; //去除前导0
while(i>0)cout<<a[i--];
四、高精度数加法
#include <iostream>
#include <cstring>
using namespace std;
int a[1015], b[1015];
void string2int(char s1[], char s2[]) {
a[0] = strlen(s1);
b[0] = strlen(s2);
for (int i = a[0], j = 0; i >= 1; i--, j++) {
a[i] = s1[j] - '0';
}
for (int i = b[0], j = 0; i >= 1; i--, j++) {
b[i] = s2[j] - '0';
}
return ;
}
void addition(int a[], int b[]) {
int len = a[0] > b[0] ? a[0] + 1 : b[0] + 1; //存储运算结果的最大位数
int flag = 0;//保存是否有进位
int temp = 0;
for (int i = 1; i <= len; i++) {
temp = a[i] + b[i] + flag;
a[i] = temp % 10;//对应位的计算结果放在a数组的对应位上
flag = temp / 10;
}
a[0] = len;
return ;
}
void print() {
int len = a[0];
while (a[len] == 0) len--; //去除先导0
while (len > 0) cout << a[len--];
return ;
}
int main() {
char s1[1010], s2[1010];
cin >> s1 >> s2;
string2int(s1, s2);
addition(a, b);
print();
return 0;
}
五、高精度数减法
#include <iostream>
#include <cstring>
using namespace std;
//高精度数减法运算(被减数大于减数)
int a[1015], b[1015];
void string2int(char s1[], char s2[]) {
a[0] = strlen(s1);
b[0] = strlen(s2);
for (int i = a[0], j = 0; i >= 1; i--, j++) {
a[i] = s1[j] - '0';
}
for (int i = b[0], j = 0; i >= 1; i--, j++) {
b[i] = s2[j] - '0';
}
return ;
}
void substraction() {
int len = a[0]; //因为被减数比减数大
int k = 0;
for (int i = 1; i <= len; i++) {
if (a[i] + k >= b[i]) {
a[i] = a[i] + k - b[i];
k = 0;
} else { //借位的情况
a[i] = a[i] + 10 + k - b[i];
k = -1;
}
}
return ;
}
void print() {
while (a[a[0]] == 0) a[0]--;
while (a[0] > 0) cout << a[a[0]--];
cout << endl;
}
int main() {
char s1[1010], s2[1010];
cin >> s1 >> s2;
string2int(s1, s2);
substraction();
print();
return 0;
}
六、高精度乘法
#include <iostream>
#include <cstring>
using namespace std;
//高精度数乘法运算
int a[1015], b[1015];
int ans[3000];
void string2int(char s1[], char s2[]) {
a[0] = strlen(s1);
b[0] = strlen(s2);
for (int i = a[0], j = 0; i > 0; i--, j++) {
a[i] = s1[j] - '0';
}
for (int i = b[0], j = 0; i > 0; i--, j++) {
b[i] = s2[j] - '0';
}
return ;
}
void multiplication() {
for (int i = 1; i <= a[0]; i++) {
for (int j = 1; j <= b[0]; j++) {
ans[i + j - 1] = ans[i + j - 1] + a[i] * b[j];
ans[i + j] = ans[i + j] + ans[i + j - 1] / 10;
ans[i + j - 1] = ans[i + j - 1] % 10;
}
}
ans[0] = a[0] + b[0];//记录结果的位数
}
void print() {
while (ans[ans[0]] == 0) ans[0]--;
while (ans[0] > 0) cout << ans[ans[0]--];
cout << endl;
}
int main() {
char s1[1010], s2[1010];
cin >> s1 >> s2;
string2int(s1, s2);
multiplication();
print();
return 0;
}