您的位置:首页 > 其它

第八周(项目三1)——分数类中的运算符重载.

2014-04-20 09:32 344 查看
/*
*烟台大学计算机学院学生
*All right reserved.
*文件名称*烟台大学计算机学院学生
*All right reserved.
*文件名称:分数类中的运算符重载
*作者:王洪海
*完成日期:2013年4月20日
*版本号:v1.0
*对任务及求解方法的描述部分:分数类中的运算符重载
*我的程序:
*/
#include<iostream>
using namespace std;
class CF
{
private:
int nume;  // 分子
int deno;  // 分母
public:
CF (int nu=0,int de=1);
void set(int nu,int de);    //置值,改变值时用
void simplify();     //化简(使分子分母没有公因子)
void output();   //输出:以8/6为例,style为0时,原样输出8/6;
CF operator+  (CF &t);
CF operator-  (CF &t);
CF operator*  (CF &t);
CF operator/  (CF &t);
bool operator>  (CF &t);
bool operator<  (CF &t);
bool operator== (CF &t);
bool operator>= (CF &t);
bool operator<= (CF &t);
bool operator!= (CF &t);
};
CF::CF(int nu,int de)
{
nume=nu;
deno=de;
}
void CF::set(int nu,int de)
{
nume=nu;
deno=de;

}
void CF::simplify()
{
int i;
int p;
if(nume>deno)
p=deno;
else
p=nume;
for(i=2;i<=p;i++)
{
if(nume%i==0&&deno%i==0)
{
nume/=i;
deno/=i;
}
}

}
void CF::output()
{
cout<<nume<<"/"<<deno<<endl;
}
CF CF::operator+  (CF &t)
{
CF t3;
int n;
if(deno==t.deno)
{
t3.deno=deno;
t3.nume=nume+t.nume;
}
else
{
t3.deno=deno*t.deno;
n=nume*t.deno;

t3.nume=n+deno*t.nume;
}
return t3;
}
CF CF::operator-  (CF &t)
{
CF t3;
if(deno==t.deno)
{
t3.deno=deno;
t3.nume=nume-t.nume;
}
else
{
t3.deno=deno*t.deno;
t3.nume=nume*t.deno-deno*t.nume;
}
return t3;
}
CF CF::operator* (CF &t)
{
CF t3;
t3.nume=nume*t.nume;
t3.deno=deno*t.deno;
return t3;
}
CF CF::operator/(CF &t)
{
CF t3;
t3.deno=deno*t.nume;
t3.nume=nume*t.deno;
return t3;
}
bool CF::operator>  (CF &t)
{
int z1,z2;
z1=nume*t.deno;   //先把两个分数同分,只比较分子大小
z2=t.nume*deno;
if(z1>z2)
return true;

return false;
}
bool CF::operator<  (CF &t)
{
int z1,z2;
z1=nume*t.deno;   //先把两个分数同分,只比较分子大小
z2=t.nume*deno;
if(z1<z2)
return true;
else
return false;
}
bool CF::operator== (CF &t)
{
int z1,z2;
z1=nume*t.deno;   //先把两个分数同分,只比较分子大小
z2=t.nume*deno;
if(z1==z2)
return true;
else
return false;
}
bool CF::operator>= (CF &t)
{
if(*this<t)
return false;
else
return true;
}
bool CF::operator<= (CF &t)
{
if(*this>t)
return false;
else
return true;
}
bool CF::operator!= (CF &t)
{
if(*this==t)
return false;
else
return true;
}
int main()
{
CF t1(2,3),t2(4,5),t;
cout<<"原本两个分数分别为:"<<endl;
t1.output();
t2.output();
cout<<"两个分数相加得: ";
t=t1+t2;
t.simplify();
t.output();
cout<<"两个分数相减得: ";
t=t1-t2;
t.simplify();
t.output();
cout<<"两个分数相乘得: ";
t=t1*t2;
t.simplify();
t.output();
cout<<"两个分数相除得: ";
t=t1/t2;
t.simplify();
t.output();
cout<<"对两个分数进行比较:"<<endl;
if(t1>t2)
cout<<"t1>t2"<<endl;
if(t1<t2)
cout<<"t1<t2"<<endl;
if(t1==t2)
cout<<"t1=t2"<<endl;
if(t1!=t2)
cout<<"t1不等于t2"<<endl;
if(t1>=t2)
cout<<"t1等于或大于t2"<<endl;
if(t1<=t2)
cout<<"t1等于或小于t2"<<endl;
return 0;
}

运行结果,如下图:



众里找错千百度,蓦然回首那错就在传值处!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: