首页 > 代码库 > [知识点]高精度加减法
[知识点]高精度加减法
#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
[知识点]高精度加减法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。