做分数的题时都可以用,但是不支持负数
class fractional{
private:
int a,b;//a/b
double origin;//小数值
public:
int gcd(int x,int y){//返回最大公约数
return (y==0)?x:gcd(y,x%y);
}
int lcm(int x,int y){//返回最小公倍数
return x*y/gcd(x,y);
}
void reduct(){//约分
int g=gcd(a,b);
a/=g;b/=g;
}
fractional():a(0),b(1),origin(0.00){}
fractional(int x,int y):a(x),b(y){//初始化
if(y<=0||x<0){
cout<<"It's not a correct fractional!";//分母不能为0,不支持负数
y=1;
}
origin=(double)1.00*a/b;
reduct();
}
void output(){//输出,可根据题目修改
cout<<a<<"/"<<b;
}
//关系运算符判断
bool operator<(fractional& fr){return this->origin<fr.origin;}
bool operator<=(fractional& fr){return this->origin<=fr.origin;}
bool operator>(fractional& fr){return !((*this)<=fr);}
bool operator>=(fractional& fr){return !((*this)<fr);}
bool operator==(fractional& fr){return this->origin==fr.origin;}
bool operator!=(fractional& fr){return !((*this)==fr);}
fractional reciprocal(fractional& fr){//返回一个分数的倒数
fractional ans(fr.b,fr.a);
return ans;
}
//四则运算
fractional operator+(fractional& fr){
fractional ans(this->a*fr.b+this->b*fr.a,this->b*fr.b);
return ans;
}
fractional operator*(fractional& fr){
fractional ans(this->a*fr.a,this->b*fr.b);
return ans;
}
fractional operator-(fractional& fr){
fractional ans(this->a*fr.b-this->b*fr.a,this->b*fr.b);
return ans;
}
fractional operator/(fractional& fr){
fractional ans(this->a*fr.b,this->b*fr.a);
return ans;
}
};
本题示例:
vector<fractional> v;
int main()
{
int n;
cin>>n;
cout<<"0/1"<<endl;
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
if(gcd(i,j)==1){
fractional f(i,j);
v.push_back(f);
}
}
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++){
v[i].output();
cout<<endl;
}
return 0;
}