在日常编程中,我们经常遇到超出标准整型(如 int、long long)表示范围的数字。例如,计算 100!(100 的阶乘)或处理加密算法中的超大整数时,普通数据类型就无能为力了。这时就需要C++大整数运算——也称为高精度计算。

C++高精度计算是指通过程序模拟人工手算的方式,对任意长度的整数进行加、减、乘、除等基本运算。由于 C++ 标准库不直接支持大整数(不像 Python 内置 int 支持任意精度),我们需要自己实现。
核心思想是:用字符串或数组存储每一位数字,然后按位模拟竖式运算。
我们将使用 std::vector 来存储数字,低位在前(便于进位处理)。例如,数字 1234 存储为 [4, 3, 2, 1]。
模拟竖式加法,逐位相加并处理进位。
#include <iostream>#include <vector>#include <string>#include <algorithm>class BigInt {public: std::vector<int> digits; // 低位在前 BigInt(std::string s) { for (int i = s.size() - 1; i >= 0; i--) { digits.push_back(s[i] - '0'); } } BigInt() {}};BigInt add(const BigInt& a, const BigInt& b) { BigInt res; int carry = 0; int i = 0; while (i < a.digits.size() || i < b.digits.size() || carry) { int sum = carry; if (i < a.digits.size()) sum += a.digits[i]; if (i < b.digits.size()) sum += b.digits[i]; res.digits.push_back(sum % 10); carry = sum / 10; i++; } return res;}BigInt subtract(const BigInt& a, const BigInt& b) { BigInt res; int borrow = 0; for (int i = 0; i < a.digits.size(); i++) { int diff = a.digits[i] - borrow; if (i < b.digits.size()) diff -= b.digits[i]; if (diff < 0) { diff += 10; borrow = 1; } else { borrow = 0; } res.digits.push_back(diff); } // 去除前导零 while (res.digits.size() > 1 && res.digits.back() == 0) res.digits.pop_back(); return res;}BigInt multiply(const BigInt& a, const BigInt& b) { BigInt res; res.digits.assign(a.digits.size() + b.digits.size(), 0); for (int i = 0; i < a.digits.size(); i++) { int carry = 0; for (int j = 0; j < b.digits.size() || carry; j++) { long long cur = res.digits[i + j] + (long long)a.digits[i] * (j < b.digits.size() ? b.digits[j] : 0) + carry; res.digits[i + j] = cur % 10; carry = cur / 10; } } // 去除前导零 while (res.digits.size() > 1 && res.digits.back() == 0) res.digits.pop_back(); return res;}int main() { std::string num1 = "12345678901234567890"; std::string num2 = "98765432109876543210"; BigInt a(num1), b(num2); BigInt sum = add(a, b); BigInt product = multiply(a, b); // 输出函数(需自行实现) printBigInt(sum); // 输出: 111111111011111111100 printBigInt(product); // 输出超大乘积 return 0;}void printBigInt(const BigInt& x) { for (int i = x.digits.size() - 1; i >= 0; i--) { std::cout << x.digits[i]; } std::cout << std::endl;}掌握大整数算法教程不仅能应对算法竞赛(如 ACM、蓝桥杯)中的高精度题目,还能加深你对计算机底层运算机制的理解。此外,在密码学、金融计算等领域,C++实现大数加减乘除是基础技能之一。
本文从零开始讲解了如何在 C++ 中实现大整数的基本运算。虽然代码看起来稍长,但只要理解“按位模拟手算”这一核心思想,就能轻松掌握。建议初学者动手敲一遍代码,调试几个例子(如 999+1、1000-1),你会豁然开朗!
记住:编程不是死记硬背,而是理解逻辑。祝你在C++高精度计算的道路上越走越远!
本文由主机测评网于2025-12-11发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126113.html