描述
程序填空,输出指定结果
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAX = 110;
class CHugeInt {
// 在此处补充你的代码
};
int main()
{
char s[210];
int n;
while (cin >> s >> n) {
CHugeInt a(s);
CHugeInt b(n);
cout << a + b << endl;
cout << n + a << endl;
cout << a + n << endl;
b += n;
cout << ++ b << endl;
cout << b++ << endl;
cout << b << endl;
}
return 0;
}
样例输入
99999999999999999999999999888888888888888812345678901234567789 12
6 6
样例输出
99999999999999999999999999888888888888888812345678901234567801
99999999999999999999999999888888888888888812345678901234567801
99999999999999999999999999888888888888888812345678901234567801
25
25
26
12
12
12
13
13
14
分析:
- 构造函数
CHugeInt(char* s)
和CHugeInt(int n)
- 重载运算符
CHugeInt& operator+(cosnt CHugeInt& c)
类+类
CHugeInt operator+(int n)
类+int
friend CHugeInt operator+(int n,CHugeInt& c)
int+类
CHugeInt operator+=(int n)
+=
CHugeInt operator++()
前置++
CHugeInt operator++(int)
后置++
friend ostream& operator<<(ostream& os,const CHugeInt c)
流插入
其中关于返回值还是引用,再具体讨论- 难点在于:如何计算加法。
首先肯定想把数组reverse过来,方便按顺序计算。然后采用的方法想到计算机系统(1)的全加器,三个输入(s1,s2和carry前一位进位),两个输出(sum和carry进位)。既创建一个临时对象,然后临时对象来存储结构。设立两个char来表示两个类对象上数组对应的元素,然后临时的int k,
k= c1+c2-'0' -'0'+carry
,然后判断k是否大于等于10,考虑下一位进位。
终止条件就是当c1\c2\carry都等于0时,终止。此处的0也表示空指针的意思对于char.
private:
char ch[210];
public:
void reverse(char *ch)
{
int i=0, j=strlen(ch)-1;
for(;i<=j;i++,j--)
swap(ch[i],ch[j]);
}
CHugeInt(const char* s)
{
memset(ch,'\0',sizeof(ch));
strcpy(ch,s);
reverse(ch);
}
CHugeInt(int n)
{
memset(ch,'\0',sizeof(ch));
sprintf(ch,"%d",n);
reverse(ch);
}
CHugeInt operator+(const CHugeInt& c)
{
CHugeInt temp(0);
int carry=0;
for(int i=0;i<210;i++)
{
char c1= ch[i];
char c2= c.ch[i];
cout<<c1<<" "<<c2<<endl;
if(c1==0&c2==0&&carry==0)
break;
if(c1==0)
c1='0';
if(c2==0)
c2='0';
int k = c1-'0'+c2-'0'+carry;
if(k>=10)
{
k=k%10;
temp.ch[i] = k+'0';
carry =1;
}
else
{
carry = 0;
temp.ch[i] = k+ '0';
}
}
return temp;
}
CHugeInt operator+(int n)
{
return *this + CHugeInt(n);
}
friend CHugeInt operator+(int n,CHugeInt& c)
{
return c + CHugeInt(n) ;
}
CHugeInt& operator+=(int n)
{
*this= *this + n;
return *this;
}
CHugeInt& operator++()
{
*this = *this + 1;
return *this ;
}
CHugeInt operator++(int a)
{
CHugeInt temp(*this);
*this = temp+CHugeInt(1);
return temp;
}
friend ostream& operator<<(ostream& os,const CHugeInt& h)
{
for(int i=strlen(h.ch)-1;i>=0;i--)
os<<h.ch[i];
return os;
}
- 新学习的函数
memset(char*,char,sizeof(char_arr)
就是将数组全设置为char
sprintf(char*,"%d",int)
就是将int以字符串形式写入char*
swap(char* s1,char* s2)
就是交换- 返回什么
类+类返回值,因为返回的temp是临时对象
其他返回值或引用都可以,看你return那怎么写,比如
return *this+1
那肯定返回值了,因为这是一个返回值的成员函数(类+类)
*this = *this+1; return *this
那可以返回引用。