首页 > 代码库 > [知识点]高精度加减法

[知识点]高精度加减法

#include <cstdio>
#include <cstring>
#define MAXN 10005

int la, lb, a[MAXN], b[MAXN], c[MAXN], get = 0;
char s1[MAXN], s2[MAXN];

void chg() {
    int lt = la, tmp[MAXN];
    la = lb, lb = lt;
    for (int i = 1; i <= la; i++) tmp[i] = b[i];
    for (int i = 1; i <= lb; i++) b[i] = a[i];
    for (int i = 1; i <= la; i++) a[i] = tmp[i];
}

void add() {
    if (la < lb) chg();
    for (int i = la; i >= la - lb + 1; i--) b[i] = b[i - la + lb];
    for (int i = 1; i <= la - lb; i++) b[i] = 0;
    for (int i = la; i >= 1; i--) c[i] += a[i] + b[i], c[i - 1] = c[i] / 10, c[i] %= 10;
}

void minus() {
    int f = 0;
    if (la < lb) f = 1, chg();
    for (int i = la; i >= la - lb + 1; i--) b[i] = b[i - la + lb];
    for (int i = 1; i <= la - lb; i++) b[i] = 0;
    for (int i = la; i >= 1; i--) {
        c[i] += a[i] - b[i];
        if (c[i] < 0) c[i] += 10, c[i - 1] -= 1;
    }
}

int main() {
    freopen("predicion.in", "r", stdin);
    freopen("predicion.out", "w", stdout);
    scanf("%s %s", s1, s2), la = strlen(s1), lb = strlen(s2);
    for (int i = 1; i <= la; i++) a[i] = s1[i - 1] - 0;
    for (int i = 1; i <= lb; i++) b[i] = s2[i - 1] - 0;
    minus();
    for (int i = 0; i <= la; i++) {
        if (!c[i] && !get) continue;
        else get = 1, printf("%d", c[i]);
    }
    return 0;
}

// 减法有bug

 

[知识点]高精度加减法