高精度加法(重载运算符)

求A+B 0<=A,B<=10100000
高精度加法(重载运算符版),在网上有很多写法,表示不能很清楚的明白其内容,这里给出一份c语言的简单版本,便于学习理解。

#include <stdio.h>
#include <string.h>
#define max(a,b) ((a)>(b)?(a):(b))
struct Data
{
    int a[100001], len;
    Data()//初始值
    {
        memset(a, 0, sizeof(a));
        len = 1;
    }
    Data operator + (const Data &A)const
    {
        Data B;
        B.len = max(len, A.len);
        for(int i = 0 ; i < B.len; i++)//边界需要注意
        {
            B.a[i] += A.a[i]+a[i];
            if(B.a[i] >= 10)
            {
                B.a[i] -= 10;//由于不会超过10,故用 -=10 代替 %10 效率更高
                B.a[i+1]++;//进位
            }
        }
        if(B.a[B.len])//考虑是否会进到B.len的下一位
            B.len++;
        return B;
    }
    void read()//读入函数
    {
        char d[100001];
        scanf("%s",d);
        int l=strlen(d);
        for(int i=0; i<l; i++)
            a[i]=d[l-i-1]-'0';
        len=l;
    }
    void write()//输出函数
    {
        for(int i = len-1; i>=0; i--)
            printf("%d", a[i]);
    }
};
Data A,B,C;
int main()
{
    A.read();
    B.read();
    C = A+B;//在进行Data之间的计算时可直接使用‘+’,原来int之间的加法运算不会被改变
    C.write();
    return 0;
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中的高精度运算符重载是指对整数进行大数运算时,通过重载运算符来实现对大数的加减乘除等操作。一般情况下,C++内置的整数类型(如int、long等)有一定的位数限制,无法处理超过其表示范围的大数。而通过运算符重载,我们可以自定义一个类来表示大数,并对其进行各种运算操作。 以下是一个简单的示例,展示了如何实现C++中的高精度运算符重载: ```cpp #include <iostream> #include <vector> using namespace std; class BigInteger { private: vector<int> digits; // 用vector存储大数的每一位 public: BigInteger() {} BigInteger(int num) { while (num > 0) { digits.push_back(num % 10); num /= 10; } } BigInteger operator+(const BigInteger& other) const { BigInteger result; int carry = 0; int i = 0; while (i < digits.size() || i < other.digits.size() || carry != 0) { int sum = carry; if (i < digits.size()) { sum += digits[i]; } if (i < other.digits.size()) { sum += other.digits[i]; } result.digits.push_back(sum % 10); carry = sum / 10; i++; } return result; } friend ostream& operator<<(ostream& os, const BigInteger& num) { for (int i = num.digits.size() - 1; i >= 0; i--) { os << num.digits[i]; } return os; } }; int main() { BigInteger a(123456789); BigInteger b(987654321); BigInteger c = a + b; cout << "a + b = " << c << endl; return 0; } ``` 在上述示例中,我们定义了一个名为BigInteger的类,用于表示大数。通过重载加法运算符`+`,我们可以实现对两个BigInteger对象的相加操作。同时,我们还重载了输出流运算符`<<`,以便能够直接输出BigInteger对象的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值