大数加法.重载实现

博客围绕网友提出的问题,实现了自定义整数类 MyInt 的加法运算。通过定义类的构造函数、赋值运算符、加法运算符等,完成了两个整数对象相加的功能,并进行了测试。代码中还涉及内存释放等操作,减法运算待后续补充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本身是一个网友发帖子问的.我帮他把加法搞定了.减法以后补上.

#include <iostream.h>
#include "string.h"
class MyInt
{

char* Integer;
bool Negative;
public:
MyInt(){};
MyInt(int len);                 
MyInt(char* s);
//~MyInt();                    此处不用.系统用自动收回.主要是字符串的空间,另起一函数来释放.
const void operator=(MyInt s)     //同类不需要用&        
{
Integer=new char[strlen(s.Integer)+1];      //私有成员一样访问.
strcpy(Integer,s.Integer);
Negative=s.Negative;
}
friend MyInt operator+(const MyInt &left,const MyInt &right);  //声明友元
void Display(){
for(int i=strlen(Integer)-1;i>=0;i--)//要倒序输出
cout<<Integer[i];
cout<<endl;
}
void freeInt()                       //在此处释放空间  释放时调用即可.类成员只提供一个CHAR *的指针,指针所指空间不应由本类释放.
{
delete Integer;
}
};
MyInt::MyInt(int len)
{
Integer=new char[len];
Negative=false;
}
MyInt::MyInt(char* s)
{
int i=strlen(s),j=0,t=0;
Negative=false;
if(s[0]=='-'||s[0]=='+')           //判断s的符号问题,如果是负号就存,其他情况不存
{
t=1;
if(s[0]=='-')
Negative=true;
Integer=new char[i];        / 改了
}
else Integer=new char[i+1];             /        改了
i--;
while (i>=t)
{
        if (s[i]<'0'||s[i]>'9')
{
cout<<"set error"<<endl;
i=-1;
}
else {Integer[j] = s[i];--i; ++j;}            //将s存进Integer
}
Integer[j]='/0';                
}
MyInt operator+(const MyInt &left,const MyInt &right)      //最好引用返回.不用也一样.
{
int i, j=0;int a;
int leftlen=strlen(left.Integer);
int rightlen=strlen(right.Integer);
int maxlen=(leftlen>rightlen?leftlen:rightlen)+1;
MyInt t(maxlen+1);
if(left.Negative==right.Negative)                         //同号时情况
{
for (i=0;i<leftlen&&i<rightlen;++i) //改为&&
{
a=left.Integer[i]-'0'+right.Integer[i]-'0'+ j;
//t.Integer[i] = left.Integer[i]-'0'+right.Integer[i]-'0'+ j;你原来的没错,只是觉得改int更清晰一点.
j = a / 10;
  t.Integer[i] = a % 10 + '0';
}
if(leftlen>rightlen)
for(;i<leftlen;i++)
{
a= left.Integer[i]-'0'+ j;
j = a / 10;
  t.Integer[i] = a % 10 + '0';
}
                  if(leftlen<rightlen)
for(;i<rightlen;i++)
{
a= right.Integer[i]-'0'+ j;/
j = a/ 10;
  t.Integer[i] = a % 10 + '0';
}
if(j){t.Integer[i]=j+48;t.Integer[i+1]=0;}
else t.Integer[i]=0;
if(left.Negative)t.Negative=true;//确定返回数的符号

}            //至此同号的情况完.(加法情况)
return t;                    
}
//这个问题解决.至于减法,那是你自己算法的事了,你自己看着添吧.加法测试成功.
void main(int argc, char* argv[])
{
MyInt iM("12555"); // 整数对象初始化
MyInt iN("123555");
MyInt iResult1;
iResult1 =iN+iM;
         iResult1.Display();
iResult1.freeInt();  //这样释放!!!!!
iM.freeInt();
iN.freeInt();
cout<<"~~~~~~~~~~~~~~ "<<endl;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值