#include
#include
using namespace std;
class CRational
{
private:
int m_nNumeraror; //分子
int m_nDenominator; //分母
public:
//默认构造函数
CRational()
{
m_nNumeraror = 0;
m_nDenominator = 1;
}
//重载构造函数
CRational(int numeraror,int denominator)
{
m_nNumeraror = numeraror;
m_nDenominator = denominator;
}
//析构函数
~CRational(){}
//简化打印数据
void Print(string str,int numeraror,int denominator)
{
if ( numeraror == denominator )
cout<
{
if ( numeraror % denominator == 0 )cout<
cout<
//分数相加
void Add(CRational & Rational)
{
int numeraror = m_nNumeraror*Rational.m_nDenominator + m_nDenominator*Rational.m_nNumeraror;
int denominator = m_nDenominator * Rational.m_nDenominator;
Print("加法",numeraror,denominator);
}
//分数相减
void Minus(CRational & Rational)
{
int numeraror = m_nNumeraror*Rational.m_nDenominator - m_nDenominator*Rational.m_nNumeraror;
int denominator = m_nDenominator * Rational.m_nDenominator;
Print("减法",numeraror,denominator);
}
//分数相乘
void Multiply(CRational & Rational)
{
int numeraror = m_nNumeraror*Rational.m_nNumeraror;
int denominator = m_nDenominator * Rational.m_nDenominator;
Print("乘法",numeraror,denominator);
}
//分数相除
void Except(CRational & Rational)
{
int numeraror = m_nNumeraror*Rational.m_nDenominator;
int denominator = m_nDenominator * Rational.m_nNumeraror;
Print("除法",numeraror,denominator);
}
};
void main()
{
CRational m_Rational_A(1,6);
CRational m_Rational_B(2,6);
m_Rational_A.Add(m_Rational_B);
m_Rational_A.Minus(m_Rational_B);
m_Rational_A.Multiply(m_Rational_B);
m_Rational_A.Except(m_Rational_B);
getchar();
}
#include
using namespace std;
class Rational
{
private:
int numeraror;//分子
int denominator;//分母
int x(int a,int b)
{
while(a=a%b)swap(a,b);
return b;
}
public:
Rational():numeraror(0),denominator(1){ }
Rational(int a):numeraror(a),denominator(1){ }
Rational(int a,int b)
{
int n = x(a,b);
numeraror = a/n;
denominator = b/n;
}
operator double()
{
return (double)numeraror/denominator;
}
const Rational operator+(const Rational& t)
{
return Rational(
this->numeraror * t.denominator + t.numeraror * this->denominator,
this->denominator * t.denominator
);
}
const Rational operator-(const Rational& t)
{
return Rational(
this->numeraror * t.denominator - t.numeraror * this->denominator,
this->denominator * t.denominator
);
}
const Rational operator*(const Rational& t)
{
return Rational(
this->numeraror * t.numeraror,
this->denominator * t.denominator
);
}
const Rational operator/(const Rational& t)
{
return Rational(
this->numeraror * t.denominator ,
t.numeraror * this->denominator
);
}
friend ostream& operator<<(ostream& os,const Rational &r);
void show(){cout<<*this<
ostream& operator<<(ostream& os,const Rational &r)
{
os<
}
int main()
{
cout<<"1/2:\t\t"<
Rational a(2,3),b;
b = Rational(1,6);
cout<<"a="< a.showf();
cout<<"b=";
b.show();
cout<<"a+b:\t"< cout<<"a-b:\t"<
}