早教吧 育儿知识 作业答案 考试题库 百科 知识分享

有理数操作c++(1)定义一个有理数类Rational,该类存放分数形式的有理数,定义私有变量x和y分别存放分子和分母,同时分子和分母要以最简单的形式存放.例如分数3/9的存放形式应该是1/3(2)

题目详情
有理数操作 c++
(1)定义一个有理数类Rational,该类存放分数形式的有理数,定义私有变量x和y分别存放分子和分母,同时分子和分母要以最简单的形式存放.例如分数3/9的存放形式应该是1/3
(2)定义带默认参数值的构造函数,默认有理数为0,即分子0,分母1
(3)定义成员函数Add、Sub、Mul、Div,分别完成两个有理数的加、减、乘、除运算,结果仍以最简形式存放
(4)以X/Y形式输出有理数
(5)以小数形式输出有理数
▼优质解答
答案和解析
class Rational{
private:
int x;
int y;
public:
Rational(int x=0,int y=1)
{
//这里做个异常判断,y=0的提示
//TODO:
int gcd=GCD(x,y);
this->x=x/gcd;
this->y=y/gcd;
}
int GCD(int x,int y)//求最大公约数,用于最简化分子分母
{
int m;
x=abs(x);//绝对值处理
y=abs(y);
if(x==0){ //如果分子等于0
m=y;
}
else{
do{
if(x>y){
int temp=y;
y=x;
x=temp;
}
}while((y=y%x)!=0);
m=x;
}
return m;
}
Rational& Add(Rational r){
this->x=this->x*r.y+this->y*r.x;
this->y=this->y*r.y;
int gcd=GCD(this->x,this->y);
this->x=this->x/gcd;
this->y=this->y/gcd;
return *this;
}
Rational& Sub(Rational r){
this->x=this->x*r.y-this->y*r.x;
this->y=this->y*r.y;
int gcd=GCD(this->x,this->y);
this->x=this->x/gcd;
this->y=this->y/gcd;
return *this;
}
Rational& Mul(Rational r){
this->x=this->x*r.x;
this->y=this->y*r.y;
int gcd=GCD(this->x,this->y);
this->x=this->x/gcd;
this->y=this->y/gcd;
return *this;
}
Rational& Div(Rational r){
//这里做个异常处理,除数为0时
//TODO:
this->x=this->x*r.y;
this->y=this->y*r.x;
int gcd=GCD(this->x,this->y);
this->x=this->x/gcd;
this->y=this->y/gcd;
return *this;
}
void PrintFractional(){//分数显示
cout