#include
using namespace std;
class Rational{
int m; // 分母
int n; // 分子
public:
Rational(int nn=1,int mm=1); //构造
bool setM( int M); // 设置分母,注意不能为零
void setN( int N); //设置分子
Rational R_add( const Rational& A); //加法操作, 返回和对象
void R_sub(Rational & A, Rational &B); //减法操作A-B
Rational R_mul(Rational & A); //乘法操作,返回乘积对象
void R_div(Rational & A, Rational &B); //除 A/B
void simple( ); //约分
void print(); //以分数形式显示,注意约分和符号
};
int main(){
Rational test;
Rational test2;
test.setN(4);
test.setM(8);
test.simple();
test.print();
test2.setN(3);
test2.setM(5);
test.R_add(test2).print();
test.R_sub(test,test2);
test.print();
test.R_mul(test);
test.print();
test.R_div(test,test2);
test.print();
}
Rational::Rational(int nn, int mm) {
n=nn;m=mm;
}
bool Rational::setM(int M) {
if(M==0)
return 0;
m=M;
return 1;
}
void Rational::setN(int N) {
n=N;
}
Rational Rational::R_add(const Rational &A) {
int M=mA.m;
int N=nA.m+A.nm;
Rational add;
add.setN(N);
add.setM(M);
add.simple();
return add;
}
void Rational::R_sub(Rational &A, Rational &B) {
int M=A.mB.m;
int N=A.nB.m-B.nA.m;
A.setM(M);
A.setN(N);
A.simple();
}
Rational Rational::R_mul(Rational &A) {
Rational mul;
mul.setN(A.nn);
mul.setM(A.mm);
mul.simple();
return mul;
}
void Rational::R_div(Rational &A, Rational &B) {
A.setN(A.nB.m);
A.setM(A.mB.n);
A.simple();
}
void Rational::print() {
simple();
cout<<n<<"/"<<m;
}
void Rational::simple() {
int max=((n>m)?n:m);
for(int i=0;i<=max;i++){
if(n%i==0&&m%i==0){
setM(m/i);
setN(n/i);
}
}
if(n<0&&m<0){
setM(-m);
setN(-n);
}
}