c++定义一个有理数类,实现有理数的加减乘除以及化简成最简分数等,要代码。问题解决了还会加分。
1个回答
2013-10-13
展开全部
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
if(b)
return gcd(b,a%b);
return a;
}
int lcm(int a,int b)
{
return a/gcd(a,b)*b;
}
class ratio
{
private:
int mole,deno;
public:
ratio(){
}
void setm(int m)
{
mole=m;
}
void setd(int d)
{
deno=d;
}
int getm()
{
return mole;
}
int getd()
{
return deno;
}
ratio(int m,int d)
{
mole=m;
deno=d;
}
ratio operator + (ratio &a)
{
int t=lcm(a.deno,this->deno);
ratio res(t/a.deno*a.mole+t/this->deno*this->mole,t);
res.most_simp();
return res;
}
ratio operator - (ratio &a)
{
int t=lcm(a.deno,this->deno);
ratio res(t/this->deno*this->mole-t/a.deno*a.mole,t);
res.most_simp();
return res;
}
ratio operator * (ratio &a)
{
ratio res(this->mole*a.mole,this->deno*a.deno);
res.most_simp();
return res;
}
ratio operator / (ratio &a)
{
ratio res(this->mole*a.deno,this->deno*a.mole);
res.most_simp();
return res;
}
void most_simp() //最简化
{
if(deno<0)
{
mole=-mole;
deno=-deno;
}
int t=gcd(mole,deno);
mole/=t;
deno/=t;
}
};
ostream& operator << (ostream &o,ratio s)
{
o<<s.getm()<<"/"<<s.getd();
return o;
}
int main()
{
ratio a(3,7),b(5,12);
ratio c=a+b;
cout<<c<<endl;
c=a-b;
cout<<c<<endl;
c=a*b;
cout<<c<<endl;
c=a/b;
cout<<c<<endl;
return 0;
}
using namespace std;
int gcd(int a,int b)
{
if(b)
return gcd(b,a%b);
return a;
}
int lcm(int a,int b)
{
return a/gcd(a,b)*b;
}
class ratio
{
private:
int mole,deno;
public:
ratio(){
}
void setm(int m)
{
mole=m;
}
void setd(int d)
{
deno=d;
}
int getm()
{
return mole;
}
int getd()
{
return deno;
}
ratio(int m,int d)
{
mole=m;
deno=d;
}
ratio operator + (ratio &a)
{
int t=lcm(a.deno,this->deno);
ratio res(t/a.deno*a.mole+t/this->deno*this->mole,t);
res.most_simp();
return res;
}
ratio operator - (ratio &a)
{
int t=lcm(a.deno,this->deno);
ratio res(t/this->deno*this->mole-t/a.deno*a.mole,t);
res.most_simp();
return res;
}
ratio operator * (ratio &a)
{
ratio res(this->mole*a.mole,this->deno*a.deno);
res.most_simp();
return res;
}
ratio operator / (ratio &a)
{
ratio res(this->mole*a.deno,this->deno*a.mole);
res.most_simp();
return res;
}
void most_simp() //最简化
{
if(deno<0)
{
mole=-mole;
deno=-deno;
}
int t=gcd(mole,deno);
mole/=t;
deno/=t;
}
};
ostream& operator << (ostream &o,ratio s)
{
o<<s.getm()<<"/"<<s.getd();
return o;
}
int main()
{
ratio a(3,7),b(5,12);
ratio c=a+b;
cout<<c<<endl;
c=a-b;
cout<<c<<endl;
c=a*b;
cout<<c<<endl;
c=a/b;
cout<<c<<endl;
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询