C++实现大数运算

大整数类

#include<iostream>
#include<cstring>
using namespace std;

/*大整数类*/
class HugeInt{
private:
	int data[30];

public:
	HugeInt(){}

	//实现字符数字相加,大整数
	HugeInt(const char *s)
	{
		for (int i = 0; i < 30; i++)
		{
			data[i] = 0;
		}
		int strlength = strlen(s);
		for (int j = 30 - strlength,i=0 ; j < 30; i++,j++)
		{
			data[j] = s[i] - '0';
		}
	}
	//实现long型相加
	HugeInt(long val){
		for (int i = 0; i < 30; i++)
		{
			data[i] = 0;
		}
		for (int j = 29; val != 0 && j >= 0; j--)
		{
			data[j] = val % 10;
			val /= 10;
		}
	}
	//重载加法运算符
	HugeInt operator+(HugeInt &rhs){
		HugeInt result;
		int carry = 0;
		for (int i = 29; i >= 0; i--)
		{
			result.data[i] = data[i] + rhs.data[i] + carry;
			if (result.data[i] > 9)
			{
				result.data[i] %= 10; //对10取余
				carry = 1; //进位
			}
			else
			{
				carry = 0;
			}
		}
		return result;
	}
	//重载输出运算符
	friend ostream &operator<<(ostream &out, HugeInt &rhs){
		int i = 0;
		for (; rhs.data[i] == 0 && i <= 29; i++); //跳过前面的0
		if (i == 30)
		{
			out << "此次运算结果为:" << 0;
		}
		else
		{
			out << "此次运算结果为:";
			for (; i <= 29; i++)
			{
				out << rhs.data[i];
			}
			out << endl;
		}
		return out;
	}
	~HugeInt(){};
};

主函数

/*主函数*/
int main(){
	HugeInt a1("122499999999999999999998");
	HugeInt a2("129999998888888887778666");
	cout << a1 + a2;
	system("pause");
	return 0;
}

运行结果

此次运算结果为:252499998888888887778664
请按任意键继续. . .
  • 0
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值