/*
*copyright (c)2015,烟台大学计算机学院
*All rights reserved
*文件名称:project.cpp
*作者:孙春红
*完成日期:2015年4月30日
*版本号:v1.0
*
*问题描述:实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除
(运算后再化简)、比较(6种关系)的运算。
*输入描述:略。
*程序输出:略。
*/
#include<iostream>
using namespace std;
class CFraction
{
private:
int nume; // 分子
int deno; // 分母
public:
//构造函数及运算符重载的函数声明
CFraction(int nu=0,int de=1):nume(nu),deno(de) {}
void simplify();
void display ();
CFraction operator +(CFraction &c);
CFraction operator -(CFraction &c);
CFraction operator *(CFraction &c);
CFraction operator /(CFraction &c);
bool operator > (CFraction &t);
bool operator < (CFraction &t);
bool operator >=(CFraction &t);
bool operator <=(CFraction &t);
bool operator ==(CFraction &t);
bool operator !=(CFraction &t);
};
//重载函数的实现
void CFraction::simplify()
{
int r,m,n;
m=deno;
n=nume;
while(r=m%n) // 求m,n的最大公约数
{
m=n;
n=r;
}
deno/=n;
nume/=n;
}
void CFraction::display()
{
cout<<"("<<nume<<"/"<<deno<<")"<<endl;
}
bool CFraction::operator > (CFraction &t)
{
if ((nume*t.deno)>(t.nume*deno))
return true;
return false;
}
bool CFraction::operator < (CFraction &t)
{
if ((nume*t.deno)<(t.nume*deno))
return true;
return false;
}
bool CFraction::operator >=(CFraction &t)
{
if (*this<t)
return false;
return true;
}
bool CFraction::operator <=(CFraction &t)
{
if (*this>t)
return false;
return true;
}
bool CFraction::operator ==(CFraction &t)
{
if (*this>t||*this<t)
return false;
return true;
}
bool CFraction::operator !=(CFraction &t)
{
if (*this==t)
return false;
return true;
}
CFraction CFraction:: operator +(CFraction &c)
{
CFraction c1;
c1.deno=deno*c.deno;
c1.nume=nume*c.deno+c.nume*deno;
c1.simplify();
return c1;
}
CFraction CFraction::operator -(CFraction &c)
{
CFraction c1;
c1.deno=deno*c.deno;
c1.nume=nume*c.deno-c.nume*deno;
c1.simplify();
return c1;
}
CFraction CFraction::operator *(CFraction &c)
{
CFraction c1;
c1.nume=nume*c.nume;
c1.deno=deno*c.deno;
c1.simplify();
return c1;
}
CFraction CFraction::operator /(CFraction &c)
{
CFraction t;
if (c.nume==0||c.deno==0)
return *this;
t.nume=nume*c.deno;
t.deno=deno*c.nume;
t.simplify();
return t;
}
int main()
{
CFraction x(1,3),y(-5,10),s;
cout<<"分数x=1/3 y=-5/10"<<endl;
s=x+y;
cout<<"x+y=";
s.display();
s=x-y;
cout<<"x-y=";
s.display();
s=x*y;
cout<<"x*y=";
s.display();
s=x/y;
cout<<"x/y=";
s.display();
x.display();
if (x>y) cout<<"大于"<<endl;
if (x<y) cout<<"小于"<<endl;
if (x==y) cout<<"等于"<<endl;
y.display();
cout<<endl;
return 0;
}
运行结果:
知识点总结:
实现分数类中的运算符重载。