高精度加法--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'};
    int a_int[MAXSIZE] = {0},
        b_int[MAXSIZE] = {0},
        c_int[MAXOUTSIZE] = {0};
    cin >> a;
    cin >> b;

    int len_a = strlen(a), len_b = strlen(b);
    memset(a_int, 0, sizeof a_int);
    memset(b_int, 0, sizeof b_int);
    memset(c_int, 0, sizeof c_int);

    //对齐
    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++)
    {
        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;
}

posted @ 2018-09-17 20:18  caibingcheng  阅读(677)  评论(0编辑  收藏  举报