学习途径:https://www.bilibili.com/video/BV1qr4y1w7mC?p=1
1.高精度加法
(处理了结果中的前导零)
思考:如果是负数如何相加代码如何写
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
//c为进位数组
//全局数组,编译器会将它的每个元素初始化为0
int a[500], b[500], c[501], ans[501], len_a, len_b, len_ans;
//存入高精度数
void Read(int* a, int& len)
{
string cur;
cin >> cur;
len = cur.length();
for (int i = 0; i < len; i++)
{
a[i] = cur[i] - '0';
}
reverse(a,a + len);
}
int main()
{
Read(a,len_a);
Read(b,len_b);
len_ans = max(len_a, len_b);
//逐位相加,逢十进一
for (int i = 0; i <= len_ans; i++)
{
ans[i] = a[i] + b[i] + c[i];
if (ans[i] > 9)
{
c[i + 1] = ans[i] / 10;
ans[i] %= 10;
}
}
//判断位数
while (ans[len_ans] > 0)
{
len_ans++;
}
//删除前导零
while (ans[len_ans-1] == 0 && len_ans > 0)
{
len_ans--;
}
//逆序输出
for (int i = len_ans - 1; i >= 0; i--)
{
cout << ans[i];
}
return 0;
}
2.高精度减法(默认被减数>减数)
(代码中未写注释,思路和加法差不多)
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
//数组a为被减数,b为减数,c为进位数组,ans为结果数组
int a[500], b[500], c[501], ans[501], len_a, len_b, len_ans;
void Read(int* a, int& len)
{
string cur;
cin >> cur;
len = cur.length();
for (int i = 0; i < len; i++)
{
a[i] = cur[i] - '0';
}
reverse(a, a + len);
}
int main()
{
Read(a, len_a);
Read(b, len_b);
len_ans = max(len_a, len_b);
for (int i = 0; i < len_ans; i++)
{
ans[i] = a[i] - b[i] - c[i];
if (ans[i] < 0)
{
ans[i] += 10;
c[i + 1]++;
}
}
while (len_ans > 1 && ans[len_ans - 1] == 0)
{
len_ans--;
}
for (int i = len_ans - 1; i >= 0; i--)
{
cout << ans[i];
}
return 0;
}
3.高精度乘法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int a[500], b[500], ans[501], len_a, len_b, len_ans;
void Read(int *a,int &len)
{
string cur;
cin >> cur;
len = cur.length();
for (int i = 0; i < len; i++)
{
a[i] = cur[i] - '0';
}
reverse(a, a + len);
}
int main()
{
Read(a, len_a);
Read(b, len_b);
len_ans = len_a + len_b - 1;
for (int i = 0; i < len_a; i++)
{
for (int j = 0; j < len_b; j++)
{
ans[i + j] += a[i] * b[j];
}
}
//处理进位
for (int i = 0; i < len_ans; i++)
{
if (ans[i] > 9)
{
ans[i + 1] += a[i] / 10;
ans[i] %= 10;
}
}
//处理位数
while (ans[len_ans])
{
len_ans++;
}
for (int i = len_ans - 1; i >= 0; i--)
{
cout << ans[i];
}
return 0;
}