/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:刘畅
* 完成日期:2015 年 4 月 25 日
* 版 本 号:v1.0
*
* 问题描述:实现分数类中的运算符重载,
在分数类中可以完成分数的加减乘除(运算后再化简)、比较(6种关系)的运算。。
* 输入描述: ;
* 程序输出: 按要求输出。
代码如下:
#include <iostream>
using namespace std;
int gcd(int x, int y);
class CFraction
{
private:
int nume;
int deno;
public:
CFraction(int n=0,int d=1)
{
nume=n;
deno=d;
}
void simplify();
void display();
CFraction operator+(const CFraction &c);
CFraction operator-(const CFraction &c);
CFraction operator*(const CFraction &c);
CFraction operator/(const CFraction &c);
bool operator>(const CFraction &c);
bool operator<(const CFraction &c);
bool operator==(const CFraction &c);
bool operator!=(const CFraction &c);
bool operator>=(const CFraction &c);
bool operator<=(const CFraction &c);
};
void CFraction::simplify()
{
int n=gcd(nume,deno);
nume/=n;
deno/=n;
}
void CFraction::display()
{
cout<<nume<<"/"<<deno<<endl;
}
int gcd(int x, int y)
{
int z;
while (y!=0)
{
z=x;
x=y;
y=z%y;
}
return x;
}
CFraction CFraction::operator+(const CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno+c.nume*deno;
c1.deno=deno*c.deno;
c1.simplify();
return c1;
}
CFraction CFraction::operator-(const CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno-c.nume*deno;
c1.deno=deno*c.deno;
c1.simplify();
return c1;
}
CFraction CFraction::operator*(const CFraction &c)
{
CFraction c1;
c1.nume=nume*c.nume;
c1.deno=deno*c.deno;
c1.simplify();
return c1;
}
CFraction CFraction:: operator/(const CFraction &c)
{
CFraction c1;
if (c.nume == 0)
return *this;
c1.nume=nume*c.deno;
c1.deno=deno*c.nume;
c1.simplify();
return c1;
}
bool CFraction::operator>(const CFraction &c)
{
int t_nume,c_nume,common_deno;
t_nume=nume*c.deno;
c_nume=c.nume*deno;
common_deno=deno*c.deno;
if ((t_nume-c_nume)*common_deno>0)
return true;
return false;
}
bool CFraction::operator<(const CFraction &c)
{
int t_nume,c_nume,common_deno;
t_nume=nume*c.deno;
c_nume=c.nume*deno;
common_deno=deno*c.deno;
if ((t_nume-c_nume)*common_deno<0)
return true;
return false;
}
bool CFraction::operator>=(const CFraction &c)
{
if (*this<c)
return false;
return true;
}
bool CFraction::operator<=(const CFraction &c)
{
if (*this>c)
return false;
return true;
}
bool CFraction::operator!=(const CFraction &c)
{
if (*this<c||*this>c)
return true;
return false;
}
bool CFraction::operator==(const CFraction &c)
{
if (*this!=c)
return false;
return true;
}
int main()
{
CFraction c1(10,5),c2(3,9),c3;
c1.display();
c2.display();
cout<<endl;
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
cout<<endl;
if (c1>c2)
cout<<"c1>c2"<<endl;
if (c1<c2)
cout<<"c1<c2"<<endl;
if (c1>=c2)
cout<<"c1>=c2"<<endl;
if (c1<=c2)
cout<<"c1<=c2"<<endl;
if (c1==c2)
cout<<"c1==c2"<<endl;
if (c1!=c2)
cout<<"c1!=c2"<<endl;
return 0;
}
运行结果: