/*
* 程序的版权和版本声明部分
* Copyright (c)2013, 烟台大学计算机学院学生
* All rightsreserved.
* 作 者: 刘明亮
* 完成日期: 2013 年 4 月 23 日
* 版本号: v1.0
* 输入描述:
* 问题描述:
* 输出:
*/
#include<iostream>
using namespace std;
int gcd(int m, int n);
class CFraction
{private:
int nume; // 分子
int deno; // 分母
public:
CFraction(int nu=0,int de=1); //构造函数,初始化用
void set(int nu=0,int de=1); //置值,改变值时用
void simplify();
void display();
CFraction operator+(CFraction &c);
CFraction operator-(CFraction &c);
CFraction operator*(CFraction &c);
CFraction operator/(CFraction &c);
CFraction operator-(); //求反
bool operator>(CFraction &c);
bool operator<(CFraction &c);
bool operator==(CFraction &c);
};
CFraction::CFraction(int nu,int de)
{
nume=nu;
deno=de;
}
void CFraction::set(int nu,int de)
{
nume=nu;
deno=de;
}
void CFraction::simplify()
{
int m=gcd(nume,deno);
deno/=m;
nume/=m;
}
void CFraction::display()
{
cout<<nume<<"/"<<deno<<endl;
}
// 求m,n的最大公约数
int gcd(int m, int n)
{
int min;
if(m<n)
{
for(min=m;min>0;--min)
{
if(m%min==0&&n%min==0)
return min;
}
}
else
{
for(min=n;min>0;--min)
{
if(m%min==0&&n%min==0)
return min;
}
}
}
CFraction CFraction::operator+(CFraction &c)
{
return CFraction(nume*c.deno+deno*c.nume,deno*c.deno);
}
CFraction CFraction::operator-(CFraction &c)
{
return CFraction(nume*c.deno-deno*c.nume,deno*c.deno);
}
CFraction CFraction::operator*(CFraction &c)
{
return CFraction(nume*c.nume,deno*c.deno);
}
CFraction CFraction::operator/(CFraction &c)
{
return CFraction(nume*c.deno,deno*c.nume);
}
CFraction CFraction::operator-()
{
return CFraction(deno,nume);
}
bool CFraction::operator>(CFraction &c)
{
if(nume*c.deno>deno*c.nume)
return true;
else
return false;
}
bool CFraction::operator<(CFraction &c)
{
if(nume*c.deno<deno*c.nume)
return true;
else
return false;
}
bool CFraction::operator==(CFraction &c)
{
if(nume*c.deno==deno*c.nume)
return true;
else
return false;
}
int main()
{
CFraction c1(1,2),c2(2,3),c3;
cout<<"c1= ";
c1.display();
c1.simplify();
cout<<"c2= ";
c2.display();
c2.simplify();
c3=c1+c2;
c3.simplify();
cout<<"c1+c2= ";
c3.display();
c3=c1-c2;
cout<<"c1-c2= ";
c3.display();
c3=c1*c2;
c3.simplify();
cout<<"c1*c2= ";
c3.display();
c3=c1/c2;
c3.simplify();
cout<<"c1/c2= ";
c3.display();
c3=-c1;
cout<<"c1求反为:\n";
c3.display();
cout<<"下面比较两个分数大小:\n";
if(c1>c2)
cout<<"c1>c2"<<endl;
if(c1<c2)
cout<<"c1<c2"<<endl;
if(c1==c2)
cout<<"c1=c2"<<endl;
return 0;
}