接第八周实验任务3,定义分数类中<<与>>运算符重载,实现分数类的输入与输出。
#include <iostream>
using namespace std;
class CFraction
{
private:
int nu;
int de;
char c;
public:
CFraction(int nu = 0,int de = 1);
void set(int nu = 0,int de = 1);
void input();
void simplify();
void output();
CFraction operator +(CFraction &a);
CFraction operator -(CFraction &a);
CFraction operator *(CFraction &a);
CFraction operator /(CFraction &a);
CFraction operator -();
bool operator>( CFraction &c);
bool operator<( CFraction &c);
bool operator==( CFraction &c);
bool operator!=( CFraction &c);
bool operator>=( CFraction &c);
bool operator<=( CFraction &c);
friend ostream & operator <<(ostream &,CFraction &);
friend istream & operator >>(istream &,CFraction &);
};
ostream & operator <<(ostream &output,CFraction &t)
{
output << t.nu << "/" <<t.de;
cout<<endl;
return output;
}
istream & operator >>(istream &input,CFraction &t)
{
input>>t.nu>>t.de;
return input;
}
void CFraction::input()
{
cout<<"输入分数按照nu/de格式"<<endl;
cin>>nu;
cin>>c;
cin>>de;
}
void CFraction::simplify()
{
int x;
if(nu>de)
x = de;
else
x = nu;
for(int i = 2; i<=x;i++)
{
if(nu%i==0&& de%i==0)
{
nu = nu/i;
de = de/i;
i = 1;
}
}
}
CFraction::CFraction(int n,int d)
{
nu = n;
de = d;
}
CFraction CFraction::operator +(CFraction &a)
{
CFraction c;
c.nu = a.nu*de+nu*a.de;
c.de = a.de*de;
return c;
}
CFraction CFraction::operator -(CFraction &a)
{
CFraction c;
c.nu = nu*a.de - a.nu*de;
c.de = a.de*de;
return c;
}
CFraction CFraction::operator *(CFraction &a)
{
CFraction c;
c.nu = nu*a.nu;
c.de = de*a.de;
return c;
}
CFraction CFraction::operator /(CFraction &a)
{
CFraction c;
c.nu = a.nu*de;
c.de = a.de*nu;
return c;
}
CFraction CFraction::operator -()
{
CFraction c;
c.de = -de;
c.nu = -nu;
return c;
}
void CFraction::output()
{
cout<<nu<<"/"<<de<<endl;
}
bool CFraction::operator>(CFraction &c)
{
if((nu*c.de - de*c.nu)>0)
return true;
else
return false;
}
// 分数比较大小
bool CFraction::operator<( CFraction &c)
{
if((nu*c.de - de*c.nu)<0)
return true;
else
return false;
}
// 分数比较大小
bool CFraction::operator==( CFraction &c)
{
if((nu*c.de - de*c.nu)==0)
return true;
else
return false;
}
// 分数比较大小
bool CFraction::operator!=( CFraction &c)
{
if((nu*c.de - de*c.nu)==0)
return false;
else
return true;
}
// 分数比较大小
bool CFraction::operator>=( CFraction &c)
{
if((nu*c.de - de*c.nu)>=0)
return true;
else
return false;
}
// 分数比较大小
bool CFraction::operator<=( CFraction &c)
{
if((nu*c.de - de*c.nu)<0)
return true;
else
return false;
}
int main()
{
CFraction a,b,c;
int t;
cout<<"请输入分数a的值"<<endl;
cin>>a;
cout<<"请输入分数b的值"<<endl;
cin>>b;
cout<<"计算分数";
cout<<a;
cout<<"与";
cout<<b;
cout<<"和";
c=a+b;
c.simplify();
cout<<c;
cout<<"差";
c=a-b;
c.simplify();
cout<<c;
cout<<"乘";
c=a*b;
c.simplify();
cout<<c;
cout<<"除";
c=a/b;
c.simplify();
cout<<c;
cout<<"对分数";
cout<<a;
cout<<"求反";
-a;
cout<<a;
if (a>b) cout<<"大于"<<endl;
if (a<b) cout<<"小于"<<endl;
if (a==b) cout<<"等于"<<endl;
system("pause");
return 0;
}