高精度减法–C++

高精度减法--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;
}

原文链接: https://www.cnblogs.com/jerry323/p/9664818.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    高精度减法--C++

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/281311

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午5:35
下一篇 2023年2月15日 上午5:37

相关推荐