#include <iostream>
#include <cstdlib>
using namespace std;
class CFraction
{
private:
int nume;
int deno;
public:
CFraction(int nu=0,int de=1);
void set(int nu,int de);
void input();
void simplify();
void output();
int gcd(int a,int b);
CFraction operator+(CFraction &c);
CFraction operator-(CFraction &c);
CFraction operator*(CFraction &c);
CFraction operator/(CFraction &c);
bool operator>(CFraction &c);
bool operator<(CFraction &c);
bool operator>=(CFraction &c);
bool operator<=(CFraction &c);
bool operator==(CFraction &c);
bool operator!=(CFraction &c);
};
CFraction::CFraction(int nu,int de)
{
if(de!=0)
{
nume=nu;
deno=de;
}
else
{
cerr<<"初始化中发生错误,程序退出\n";
exit(0);
}
}
void CFraction::input()
{
int nu,de;
char c;
cout<<"请输入分数:";
while(1)
{
cin>>nu>>c>>de;
if(c!='/')
{
cout<<"格式错误!"<<endl;
continue;
}
else if(de==0)
{
cout<<"格式错误!"<<endl;
continue;
}
else
break;
}
nume=nu;
deno=de;
}
int CFraction::gcd(int a,int b)
{
int r;
while(a!=0)
{
r=a%b;
a=r;
b=r;
}
return a;
}
void CFraction::set(int nu,int de)
{
if(de!=0)
{
nume=nu;
deno=de;
}
}
void CFraction::simplify()
{
int a;
a=gcd(nume,deno);
nume/=a;
deno/=a;
}
void CFraction::output()
{
cout<<nume<<"/"<<deno<<endl;
}
CFraction CFraction::operator+(CFraction &c)
{
CFraction t;
t.nume=nume*c.deno+c.nume*deno;
t.deno=deno*c.deno;
t.simplify();
return t;
}
CFraction CFraction::operator-(CFraction &c)
{
CFraction t;
t.nume=nume*c.deno-c.nume*deno;
t.deno=deno*c.deno;
t.simplify();
return t;
}
CFraction CFraction::operator*(CFraction &c)
{
CFraction t;
t.deno=deno*c.deno;
t.nume=nume*c.nume;
t.simplify();
return t;
}
CFraction CFraction::operator/(CFraction &c)
{
if (!c.nume) {
cout<<"运算错误!\n";
return *this;
}
CFraction t;
t.deno=deno*c.nume;
t.nume=nume*c.deno;
t.simplify();
return t;
}
bool CFraction::operator>(CFraction &c)
{
CFraction t;
t=*this-c;
if(t.nume*t.deno>0)
return true;
else
return false;
}
bool CFraction::operator<(CFraction &c)
{
CFraction t;
t=*this-c;
if(t.nume*t.deno<0)
return true;
else
return false;
}
bool CFraction::operator>=(CFraction &c)
{
if(*this<c)
return false;
else
return false;
}
bool CFraction::operator<=(CFraction &c)
{
if(*this>c)
return false;
else
return true;
}
bool CFraction::operator==(CFraction &c)
{
CFraction t;
t=*this-c;
if(t.nume*t.deno==0)
return true;
else
return false;
}
bool CFraction::operator!=(CFraction &c)
{
if(*this==c)
return false;
else
return true;
}
int main()
{
CFraction x(1,2),y(1,3),t;
cout<<"两个分数分别为 x=1/2,y=1/3"<<endl;
t=x-y;
cout<<"x-y=";
t.output();
t=x+y;
cout<<"x+y=";
t.output();
t=x*y;
cout<<"x*y=";
t.output();
t=x/y;
cout<<"x/y=";
t.output();
x.output();
if(x>y) cout<<"大于"<<endl;
if(x<y) cout<<"小于"<<endl;
if(x>=y) cout<<"大于等于"<<endl;
if(x<=y) cout<<"小于等于"<<endl;
if(x==y) cout<<"等于"<<endl;
if(x!=y) cout<<"不等于"<<endl;
y.output();
return 0;
}
运行到一半就停止运行,找不出原因= =。