高精度减法
作者:
浩然正气
,
2024-11-14 10:01:41
,
所有人可见
,
阅读 4
高精度减法C
语言
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define N 100010
bool cmp(char str1[], char str2[])
{
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len1 != len2)
return len1 > len2;
for (int i = 0; i < len1; i ++ )
{
if (str1[i] != str2[i])
return str1[i] > str2[i];
}
return true;
}
void sub(char str1[], char str2[], char sub_high[])
{
int len1 = strlen(str1);
int len2 = strlen(str2);
// 1. 将字符数组转换成整数数组,第0位存储个位数字
int a[N] = {0};
int b[N] = {0};
for (int i = 0; i < len1; i ++ )
a[i] = str1[len1 - i - 1] - '0';
for (int i = 0; i < len2; i ++ )
b[i] = str2[len2 - i - 1] - '0';
// 2. 减法过程
int index = 0;
int res[N] = {0};
int t = 0; // 借位
for (int i = 0; i < len1 || i < len2; i ++ )
{
if (i < len1) t = a[i] - t;
if (i < len2) t = t - b[i];
res[index ++] = (t + 10) % 10;
if (t >= 0) t = 0;
else t = 1;
}
// 3. 去除前导0
int happy = 0;
bool zero_index = true;
for (int i = index - 1; i >= 0; i -- )
{
if (res[i] == 0 && zero_index == true)
continue;
else
{
zero_index = false; // 结束前导0
sub_high[happy ++] = res[i] + '0';
}
}
if (zero_index == true)
strcpy(sub_high, "0");
}
int main()
{
char str1[N] = "";
char str2[N] = "";
char sub_high[N] = "";
scanf("%s", str1);
scanf("%s", str2);
if (cmp(str1, str2))
{
sub(str1, str2, sub_high);
puts(sub_high);
}
else
{
sub(str2, str1, sub_high);
printf("-%s\n", sub_high);
}
return 0;
}