您的位置:首页 > 其它

第八周 项目3--实现分数类中的运算符重载

2014-04-17 08:56 363 查看
/*
*程序的版权和版本声明部分:
*Copyright(c)2013,烟台大学计算机学院学生
*All rights reserved.
*文件名称:
*作者:尚振伟
*完成日期:2014年4月17日
*版本号:v0.1
*对任务及求解方法的描述部分:
*输入描述:无
*问题描述:实现分数类中的运算符重载
*程序输入:
*程序输出:
*问题分析:
*算法设计:
*我的程序:
*/
#include <iostream>
#include <Cmath>
using namespace std;
class CFtra
{
private:
int nume;
int deno;
public:
CFtra(int n=0,int d=0):nume(n),deno(d) {}
int gcd(int,int);
void simplify();
void display();
CFtra operator+(CFtra &c);
CFtra operator-(CFtra &c);
CFtra operator*(CFtra &c);
CFtra operator/(CFtra &c);
bool operator>(const CFtra &c);
bool operator<(const CFtra &c);
bool operator==(const CFtra &c);
bool operator!=(const CFtra &c);
bool operator>=(const CFtra &c);
bool operator<=(const CFtra &c);
};
int CFtra::gcd(int a,int b)
{
int m,n;   //n代表x,y的最大公约数
if(a<b)
{
m=a;
a=b;
b=m;
}
if(b==0)
{
n=a;
}
else
{
n=gcd(b,a%b);
}
return n;
}
void CFtra::simplify()
{
int r;
r=gcd(nume,deno);
deno/=r;
nume/=r;
}
CFtra CFtra::operator+(CFtra &c)
{
CFtra t;
t.nume=nume*c.deno+deno*c.nume;
t.deno=deno*c.deno;
return t;
}
CFtra CFtra::operator-(CFtra &c)
{
CFtra t;
t.nume=nume*c.deno-deno*c.nume;
t.deno=deno*c.deno;
t.simplify();
return t;
}
CFtra CFtra::operator*(CFtra &c)
{
CFtra t;
t.nume=nume*c.nume;
t.deno=deno*c.deno;
return t;
}
CFtra CFtra::operator/(CFtra &c)
{
CFtra t;
if (!c.nume) return *this;
t.nume=nume*c.deno;
t.deno=deno*c.nume;
return t;
}
bool CFtra::operator>(const CFtra &c)
{
if((*this).nume*c.deno>(*this).deno*c.nume)
{
return true;
}
else
{
return false;
}
}
bool CFtra::operator<(const CFtra &c)
{
if((*this).nume*c.deno<(*this).deno*c.nume)
{
return true;
}
else
{
return false;
}
}
bool CFtra::operator!=(const CFtra &c)
{
if(*this>c||*this<c)
{
return true;
}
else
{
return false;
}
}
bool CFtra::operator==(const CFtra &c)
{
if(!(*this!=c))
{
return true;
}
else
{
return false;
}
}
bool CFtra::operator<=(const CFtra &c)
{
if(!(*this>c))
{
return true;
}
else
{
return false;
}
}
bool CFtra::operator>=(const CFtra &c)
{
if(!(*this<c))
{
return true;
}
else
{
return false;
}
}
void CFtra::display()
{
if(nume==deno)
{
cout<<"1"<<endl;
}
if(nume>deno)
{
cout<<nume/deno;
cout<<"("<<nume%deno<<"/"<<deno<<")"<<endl;
}
else
{
cout<<nume<<"/"<<deno<<endl;
}
}
int main()
{
CFtra x(3,8),y(2,10),c;
x.simplify();
cout<<"x=";
x.display();
y.simplify();
cout<<"y=";
y.display();
c=x+y;
c.simplify();
cout<<"x+y=";
c.display();
c=x-y;
cout<<"x-y=";
c.display();
c=x*y;
c.simplify();
cout<<"x*y=";
c.display();
c=x/y;
c.simplify();
cout<<"x/y=";
c.display();
if (x>y) cout<<"x>y"<<endl;
if (x<y) cout<<"x<y"<<endl;
if (x==y) cout<<"x=y"<<endl;
if (x!=y) cout<<"x!=y"<<endl;
if (x<=y) cout<<"x<=y"<<endl;
if (x>=y) cout<<"x>=y"<<endl;
cout<<endl;
return 0;
}


结果展示:



心得体会:为啥前面的分数小于后面的分数程序就出错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: