问题及代码:
/*
*Copyright (c) 2015,烟台大学计算机学院
*All rights reserved.
*文件名称:text.cpp
*作者:徐健
*完成日期:2015年23日
*版本号:v1.0
*
*问题描述: 实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、比较(6种关系)的运算
*输入描述: 无
*程序输出: 加减乘除之后的结果
*/
#include <iostream>
#include<cmath>
using namespace std;
class CFraction
{
private:
int nume; // 分子
int deno; // 分母
public:
//构造函数及运算符重载的函数声明
CFraction(int nume=1,int deno=1);
void huajian();
CFraction operator+(CFraction &c);
CFraction operator-(CFraction &c);
CFraction operator*(CFraction &c);
CFraction operator/(CFraction &c);
friend ostream& operator <<(ostream &out,CFraction c);
friend istream& operator >>(istream &in,CFraction &c);
void show();
};
CFraction::CFraction(int nume,int deno):nume(nume),deno(deno){}
void CFraction::huajian()
{
int m,n,r;
n=fabs(deno);
m=fabs(nume);
while(r=m%n)
{
m=n;
n=r;
}
deno/=n;
nume/=n;
if (deno<0)
{
deno=-deno;
nume=-nume;
}
}
CFraction CFraction::operator+(CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno+c.nume*deno;
c1.deno=deno*c.deno;
c1.huajian();
return c1;
}
CFraction CFraction::operator-(CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno-c.nume*deno;
c1.deno=deno*c.deno;
c1.huajian();
return c1;
}
CFraction CFraction::operator*(CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno*c.nume*deno;
c1.deno=deno*c.deno;
c1.huajian();
return c1;
}
CFraction CFraction::operator/(CFraction &c)
{
CFraction c1;
c1.nume=nume*c.deno/c.nume*deno;
c1.deno=deno*c.deno;
c1.huajian();
return c1;
}
ostream& operator <<(ostream&out,CFraction c)
{
cout<<c.nume<<'/'<<c.deno;
return cout;
}
istream &operator >>(istream &in,CFraction &c)
{
char ch;
while(1)
{
cin>>c.nume>>ch>>c.deno;
if (c.deno==0)
cerr<<"分母为0, 请重新输入\n";
else if(ch!='/')
cerr<<"格式错误(形如m/n)! 请重新输入\n";
else
break;
}
return cin;
}
//重载函数的实现及用于测试的main()函数
int main()
{
CFraction c1,c2;
CFraction c3;
cin>>c1;
cin>>c2;
c3=c1+c2;
cout<<c3<<endl;
c3=c1-c2;
cout<<c3<<endl;
c3=c1*c2;
cout<<c3<<endl;
c3=c1/c2;
cout<<c3<<endl;
return 0;
}
运行结果: