大整数类
#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
请按任意键继续. . .