#include<iostream>
using namespace std;
namespace gra {
int gcd(int a,int b) {
if (b==0) return a;
return gcd(b,a%b);
}
int lcm(int a,int b) {
return a*b/gcd(a,b);
}
struct graeds {
int son;
int mum;
double dou() {
return (double)son/(double)mum;
}
void sim() {
int temp=gcd(mum,son);
son/=temp;
mum/=temp;
}
void pass(graeds &b) {
int temp=lcm(mum,b.mum);
son*=(temp/mum);
mum=temp;
b.son*=(temp/b.mum);
b.mum=temp;
}
graeds operator+(const graeds b)const {
graeds tmp=b;
graeds tmp2;
tmp2.son=son;
tmp2.mum=mum;
tmp.pass(tmp2);
tmp.son+=tmp2.son;
tmp.sim();
return tmp;
}
graeds operator-(const graeds b)const {
graeds tmp=b;
graeds tmp2;
tmp2.mum=mum;
tmp2.son=son;
tmp.pass(tmp2);
if (tmp2.son-tmp.son<0) {
tmp2.mum=0;
tmp2.son=0;
return tmp2;
}
tmp2.son-=tmp.son;
tmp2.sim();
return tmp2;
}
graeds operator*(const graeds b)const {
graeds tmp=b;
graeds tmp2;
tmp2.mum=mum;
tmp2.son=son;
tmp.mum*=tmp2.mum;
tmp.son*=tmp2.son;
tmp.sim();
return tmp;
}
graeds operator/(const graeds b)const {
graeds tmp;
tmp.son=b.mum;
tmp.mum=b.son;
graeds tmp2;
tmp2.mum=mum;
tmp2.son=son;
tmp2=tmp2*tmp;
return tmp2;
}
graeds operator+=(const graeds b) {
graeds tmp=b;
graeds tmp2;
tmp2.son=son;
tmp2.mum=mum;
tmp2=tmp2+tmp;
son=tmp2.son;
mum=tmp2.mum;
return tmp2;
}
graeds operator-=(const graeds b) {
graeds tmp=b;
graeds tmp2;
tmp2.son=son;
tmp2.mum=mum;
tmp2=tmp2-tmp;
son=tmp2.son;
mum=tmp2.mum;
return tmp2;
}
graeds operator*=(const graeds b) {
graeds tmp=b;
graeds tmp2;
tmp2.son=son;
tmp2.mum=mum;
tmp2=tmp2*tmp;
son=tmp2.son;
mum=tmp2.mum;
return tmp2;
}
graeds operator/=(const graeds b) {
graeds tmp=b;
graeds tmp2;
tmp2.son=son;
tmp2.mum=mum;
tmp2=tmp2/tmp;
son=tmp2.son;
mum=tmp2.mum;
return tmp2;
}
bool operator==(graeds b) {
if (dou()==b.dou()) {
return true;
}
return false;
}
bool operator<(graeds b) {
if (dou()<b.dou()) {
return true;
}
return false;
}
bool operator>(graeds b) {
if (dou()>b.dou()) {
return true;
}
return false;
}
bool operator!=(graeds b) {
if (dou()!=b.dou()) {
return true;
}
return false;
}
bool operator<=(graeds b) {
if (dou()<=b.dou()) {
return true;
}
return false;
}
bool operator>=(graeds b) {
if (dou()>=b.dou()) {
return true;
}
return false;
}
graeds operator=(const graeds b) {
son=b.son;
mum=b.mum;
return b;
}
friend istream & operator>> (istream &in, graeds &A){
char a;
in>>A.son>>a>>A.mum;
if (a!='/'){
A.son=0;
A.mum=0;
}
return in;
}
friend ostream & operator<< (ostream &out, graeds &A){
out<<A.son<<"/"<<A.mum;
return out;
}
};
}
这是我新完成的一个能存储及输入,输出分数的头文件,希望能帮助大家