高精度减法--C++

19 篇文章 0 订阅
18 篇文章 0 订阅

高精度减法–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] = {'\0'},
         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 ('\0' != c[i])
        {
            cout << c[i];
        }
    }

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值