C++怎么实现一个高精度的数值计算类

来源:程序开发作者:柬埔寨程序员头衔:程序员
导读:本期聚焦于小伙伴创作的《C++怎么实现一个高精度的数值计算类》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C++怎么实现一个高精度的数值计算类》有用,将其分享出去将是对创作者最好的鼓励。

在C++的实际开发中,内置的int、long long等整数类型都有明确的数值范围,当需要处理超过这些范围的超长整数运算时,就需要自己实现高精度的数值计算类。我们可以通过字符串存储大数,再结合运算符重载实现各类运算,让自定义类的使用体验和内置数值类型一致。

类的整体设计

高精度数值计算类的核心是用字符串保存超长整数的每一位,同时需要记录数值的正负属性。我们定义类名为BigInteger,成员变量包含两个私有属性:一个字符串用于存储数值的绝对值,一个布尔值用于标记是否为负数。

成员变量与构造方法

构造方法需要支持从字符串和内置整数类型初始化,同时需要处理前导零和正负号的情况。具体实现代码如下:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;

class BigInteger {
private:
    string num;       // 存储数值的绝对值,逆序存储方便运算
    bool isNegative;  // 标记是否为负数

    // 去除前导零的辅助函数
    void removeLeadingZeros() {
        while (num.size() > 1 && num.back() == '0') {
            num.pop_back();
        }
    }

public:
    // 默认构造,初始化为0
    BigInteger() : num("0"), isNegative(false) {}

    // 从字符串构造
    BigInteger(const string& s) {
        if (s.empty()) {
            num = "0";
            isNegative = false;
            return;
        }
        int start = 0;
        if (s[0] == '-') {
            isNegative = true;
            start = 1;
        } else {
            isNegative = false;
        }
        // 跳过前导零
        while (start < s.size() && s[start] == '0') {
            start++;
        }
        if (start == s.size()) {
            num = "0";
            isNegative = false;
        } else {
            num = s.substr(start);
            reverse(num.begin(), num.end()); // 逆序存储,低位在前
        }
    }

    // 从long long构造
    BigInteger(long long n) {
        if (n < 0) {
            isNegative = true;
            n = -n;
        } else {
            isNegative = false;
        }
        if (n == 0) {
            num = "0";
        } else {
            num.clear();
            while (n > 0) {
                num.push_back((n % 10) + '0');
                n /= 10;
            }
        }
    }
};

比较运算符重载

实现加减乘除运算前,需要先实现比较运算符,方便判断两个大数的大小关系。我们重载<>==等运算符,比较逻辑需要先判断正负,再比较绝对值大小。

    // 重载==运算符
    bool operator==(const BigInteger& other) const {
        return num == other.num && isNegative == other.isNegative;
    }

    // 重载!=运算符
    bool operator!=(const BigInteger& other) const {
        return !(*this == other);
    }

    // 重载<运算符
    bool operator<(const BigInteger& other) const {
        // 正负不同的情况
        if (isNegative != other.isNegative) {
            return isNegative;
        }
        // 同正的情况
        if (!isNegative) {
            if (num.size() != other.num.size()) {
                return num.size() < other.num.size();
            }
            // 位数相同,从高位到低位比较
            string a = num, b = other.num;
            reverse(a.begin(), a.end());
            reverse(b.begin(), b.end());
            return a < b;
        }
        // 同负的情况,绝对值大的反而小
        if (num.size() != other.num.size()) {
            return num.size() > other.num.size();
        }
        string a = num, b = other.num;
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        return a > b;
    }

    // 重载>运算符
    bool operator>(const BigInteger& other) const {
        return other < *this;
    }

    // 重载<=运算符
    bool operator<=(const BigInteger& other) const {
        return !(*this > other);
    }

    // 重载>=运算符
    bool operator>=(const BigInteger& other) const {
        return !(*this < other);
    }

加法运算符重载

加法需要考虑两个大数同号和异号的情况,异号时实际是做减法运算。我们先将加法逻辑拆分为同号相加和异号相减的辅助函数,再在重载的+运算符中调用。

private:
    // 两个非负大数相加,返回结果字符串(逆序)
    static string addAbs(const string& a, const string& b) {
        string res;
        int carry = 0;
        int i = 0, j = 0;
        while (i < a.size() || j < b.size() || carry) {
            int sum = carry;
            if (i < a.size()) sum += a[i++] - '0';
            if (j < b.size()) sum += b[j++] - '0';
            res.push_back((sum % 10) + '0');
            carry = sum / 10;
        }
        return res;
    }

    // 两个非负大数相减,a >= b,返回结果字符串(逆序)
    static string subAbs(const string& a, const string& b) {
        string res;
        int borrow = 0;
        int i = 0, j = 0;
        while (i < a.size()) {
            int diff = (a[i] - '0') - borrow;
            if (j < b.size()) diff -= (b[j] - '0');
            if (diff < 0) {
                diff += 10;
                borrow = 1;
            } else {
                borrow = 0;
            }
            res.push_back(diff + '0');
            i++;
            j++;
        }
        // 去除结果中的前导零
        while (res.size() > 1 && res.back() == '0') {
            res.pop_back();
        }
        return res;
    }

public:
    // 重载+运算符
    BigInteger operator+(const BigInteger& other) const {
        BigInteger res;
        if (isNegative == other.isNegative) {
            // 同号,绝对值相加,符号不变
            res.num = addAbs(num, other.num);
            res.isNegative = isNegative;
        } else {
            // 异号,比较绝对值大小
            BigInteger a = *this, b = other;
            if (a.isNegative) {
                a.isNegative = false;
                b.isNegative = false;
                if (a > b) {
                    res.num = subAbs(a.num, b.num);
                    res.isNegative = true;
                } else {
                    res.num = subAbs(b.num, a.num);
                    res.isNegative = false;
                }
            } else {
                b.isNegative = false;
                if (*this >= other) {
                    res.num = subAbs(num, other.num);
                    res.isNegative = false;
                } else {
                    res.num = subAbs(other.num, num);
                    res.isNegative = true;
                }
            }
        }
        res.removeLeadingZeros();
        return res;
    }

输出运算符重载

为了让BigInteger对象可以直接用cout输出,我们需要重载<<运算符,输出时先输出负号(如果是负数),再逆序输出存储的数值字符串。

// 重载输出运算符,需要声明为友元函数
friend ostream& operator<<(ostream& os, const BigInteger& bigInt) {
    if (bigInt.isNegative) {
        os << '-';
    }
    string tmp = bigInt.num;
    reverse(tmp.begin(), tmp.end());
    os << tmp;
    return os;
}

使用示例

完成上述核心功能后,我们可以测试这个高精度类的使用效果,代码如下:

int main() {
    BigInteger a("12345678901234567890");
    BigInteger b("-98765432109876543210");
    BigInteger c = a + b;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "a + b = " << c << endl;

    BigInteger d(12345);
    BigInteger e("99999999999999999999");
    BigInteger f = d + e;
    cout << "d = " << d << endl;
    cout << "e = " << e << endl;
    cout << "d + e = " << f << endl;
    return 0;
}

上述代码运行后,会正确输出超长整数的加法结果,证明了我们实现的高精度类的可用性。如果需要扩展减法、乘法、除法等运算,可以参考加法的实现思路,结合大数运算的常规算法补充对应的运算符重载即可。

C++大数运算运算符重载高精度数值计算修改时间:2026-07-23 12:36:53

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。