高精度减法--C++
仿照竖式减法,先对其,再对应位相减。
算法处理时,先比较大小,用大的减小的,对应位再比较大小,用于作为借位符。
#include <iostream>
#include <cstring>
#define MAXSIZE 20
#define MAXOUTSIZE MAXSIZE + 2
using namespace std;
int main()
{
char a[MAXSIZE] = {'0'},
b[MAXSIZE] = {'0'},
c[MAXOUTSIZE] = {' '},
t[MAXSIZE] = {'0'};
int a_int[MAXSIZE] = {0},
b_int[MAXSIZE] = {0},
c_int[MAXOUTSIZE] = {0};
cin >> a;
cin >> b;
memset(a_int, 0, sizeof a_int);
memset(b_int, 0, sizeof b_int);
memset(c_int, 0, sizeof c_int);
//考虑是否交换,大数减小数
bool minus = false;
if ((strlen(a) < strlen(b)) ||
(strcmp(a, b) < 0))
{
strcpy(t, a);
strcpy(a, b);
strcpy(b, t);
minus = true;
}
if(minus)
{
cout << "-";
}
int len_a = strlen(a), len_b = strlen(b);
//对齐
for (int i = len_a - 1, j = 0; i >= 0; i--, j++)
{
a_int[j] = a[i] - '0';
}
for (int i = len_b - 1, j = 0; i >= 0; i--, j++)
{
b_int[j] = b[i] - '0';
}
//对应位相减
for (int i = 0; i < MAXSIZE; i++)
{
//考虑是否借位
if (a_int[i] < b_int[i])
{
a_int[i] += 10;
a_int[i + 1]--;
}
c_int[i] = a_int[i] - b_int[i];
}
int ans_len = 0;
for (int i = 0; i < MAXOUTSIZE - 1; i++)
{
c_int[i + 1] += c_int[i] / 10;
c_int[i] %= 10;
ans_len = i;
}
while (c_int[ans_len] == 0)
{
ans_len--;
}
if (ans_len < 0)
{
cout << "0";
return 0;
}
for (int i = ans_len; i >= 0; i--)
{
c[i] = c_int[i] + '0';
}
for (int i = MAXOUTSIZE - 1; i >= 0; i--)
{
if (' ' != c[i])
{
cout << c[i];
}
}
return 0;
}