oj题目:
设计一个简单的SmallInt类,用来表示从-128到127之间的整数。类的唯一的数据成员val存放一个-128到127(包含-128和127这两个数)之间的整数。根据给定的main函数设计必要的成员函数。main函数已给定,提交时只需要提交main函数外的代码部分。
【注意】构造SmallInt类对象时,当给定整数不在指定范围时,需要做相应正规化处理。所谓正规化处理就是当成员数据val的值大于127时,就要减去256,当val的值小于-128时,就需要加上256,直到满足要求为止。
int main()
{
int cas=0;
SmallInt s1,s2;
while(cin>>s1>>s2)
{
cas++;
cout<<"Case "<<cas<<":"<<endl;
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"s1+s2="<<s1+s2<<endl;
cout<<"s1-s2="<<s1-s2<<endl;
cout<<"s1*s2="<<s1*s2<<endl;
cout<<"s1/s2="<<s1/s2<<endl;
}
return 0;
}
Input
包含多组数据(数据均正确合法)
每组输入数据一行,包含2个整数。
Output
对于每组测试数据的输出结果见Sample Output。
Sample Input
1 2
128 -128
256 128
Sample Output
Case 1:
s1=1
s2=2
s1+s2=3
s1-s2=-1
s1*s2=2
s1/s2=0
Case 2:
s1=-128
s2=-128
s1+s2=0
s1-s2=0
s1*s2=0
s1/s2=1
Case 3:
s1=0
s2=-128
s1+s2=-128
s1-s2=-128
s1*s2=0
s1/s2=0
下面是程序:
#include<iostream>
using namespace std;
class SmallInt
{
int val;
public:
SmallInt(){ val=0; }
SmallInt(int n)
{
while(n<-128)
n+=256;
while(n>127)
n-=256;
val=n;
}
/* SmallInt(SmallInt &s)
{val=s.val;} */
~SmallInt(){}
void Set(int n)
{
while(n<-128)
n+=256;
while(n>127)
n-=256;
val=n;
}
SmallInt operator+(SmallInt &s);
SmallInt operator-(SmallInt &s);
SmallInt operator*(SmallInt &s);
SmallInt operator/(SmallInt &s);
int GetInt(){return val;}
friend ostream& operator<<(ostream &out,SmallInt s);
};
SmallInt SmallInt::operator+(SmallInt &s)//重载‘+’
{
SmallInt s1;
s1.val=val+s.val;
while(s1.val<-128)s1.val+=256;
while(s1.val>127)s1.val-=256;
return s1;
}
SmallInt SmallInt::operator-(SmallInt &s)//重载‘-’
{
SmallInt s1;
s1.val=val-s.val;
while(s1.val<-128)s1.val+=256;
while(s1.val>127)s1.val-=256;
return s1;
}
SmallInt SmallInt::operator*(SmallInt &s)//重载‘*’
{
SmallInt s1;
s1.val=val*s.val;
while(s1.val<-128)s1.val+=256;
while(s1.val>127)s1.val-=256;
return s1;
}
SmallInt SmallInt::operator/(SmallInt &s)//重载‘/’
{
SmallInt s1;
s1.val=val/s.val;
while(s1.val<-128)s1.val+=256;
while(s1.val>127)s1.val-=256;
return s1;
}
istream& operator>>(istream &in,SmallInt &s)//重载输入
{
int n;
in>>n;
s.Set(n);
return in;
}
ostream& operator<<(ostream &out,SmallInt s)//重载输出
{
out<<s.val;
return out;
}
int main()
{
int cas=0;
SmallInt s1,s2;
while(cin>>s1>>s2)
{
cas++;
cout<<"Case "<<cas<<":"<<endl;
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"s1+s2="<<s1+s2<<endl;//对应bug,这里会开始报错
cout<<"s1-s2="<<s1-s2<<endl;
cout<<"s1*s2="<<s1*s2<<endl;
cout<<"s1/s2="<<s1/s2<<endl;
}
return 0;
}
bug:
如果使用复制构造函数,和输出运算符重载的SmallInt的引用&,codeblock会报错。
待我学成归来,再解决。加油,代码人!