定义一个有理数类。一个有理数类是一个可以表示成两个整数相除的数,如1/2、2/3、4/5。一个有理数类有两个整数成员表示:分子和分母。要求能检测分母为0问题,能化简,重载+、-、*、/运算符完成四则运算,重载“==”符号判断两个有理数是否相等的原理是什么
时间: 2024-05-01 12:17:57 浏览: 174
好的,我明白了。这里是一个定义有理数类的示例代码:
```c++
#include<iostream>
using namespace std;
class RationalNumber
{
public:
int numerator; // 分子
int denominator; // 分母
public:
RationalNumber(int n=0,int d=1) // 构造函数
{
numerator=n;
denominator=d;
simplify(); // 化简
}
void simplify() // 化简
{
int m=gcd(numerator,denominator);
numerator/=m;
denominator/=m;
}
int gcd(int a,int b) // 最大公约数
{
if(b==0) return a;
return gcd(b,a%b);
}
bool is_zero() // 检测分母为0
{
if(denominator==0) return true;
else return false;
}
RationalNumber operator + (RationalNumber &anoth){ // 重载加号
RationalNumber result(numerator*anoth.denominator+anoth.numerator*denominator,denominator*anoth.denominator);
return result;
}
RationalNumber operator - (RationalNumber &anoth){ // 重载减号
RationalNumber result(numerator*anoth.denominator-anoth.numerator*denominator,denominator*anoth.denominator);
return result;
}
RationalNumber operator * (RationalNumber &anoth){ // 重载乘号
RationalNumber result(numerator*anoth.numerator,denominator*anoth.denominator);
return result;
}
RationalNumber operator / (RationalNumber &anoth){ // 重载除号
RationalNumber result(numerator*anoth.denominator,denominator*anoth.numerator);
return result;
}
bool operator == (RationalNumber &anoth){ // 重载等号
if(numerator==anoth.numerator && denominator==anoth.denominator) return true;
else return false;
}
};
int main()
{
RationalNumber rn1(1,2),rn2(2,3);
RationalNumber sum=rn1+rn2;
RationalNumber dif=rn1-rn2;
RationalNumber pro=rn1*rn2;
RationalNumber quo=rn1/rn2;
cout<<"rn1+rn2="<<sum.numerator<<"/"<<sum.denominator<<endl;
cout<<"rn1-rn2="<<dif.numerator<<"/"<<dif.denominator<<endl;
cout<<"rn1*rn2="<<pro.numerator<<"/"<<pro.denominator<<endl;
cout<<"rn1/rn2="<<quo.numerator<<"/"<<quo.denominator<<endl;
if(rn1==rn2) cout<<"rn1==rn2"<<endl;
else cout<<"rn1!=rn2"<<endl;
return 0;
}
```
以上代码中,将有理数类的整数分子和整数分母封装在了一个类里,类中包含构造函数、化简方法、检测分母为0方法、加、减、乘、除、等于运算符重载方法。
阅读全文