定义一个有理数类。一个有理数类是一个可以表示成两个整数相除的数,如1/2、2/3、4/5。一个有理数类有两个整数成员表示:分子和分母。要求能检测分母为0问题,能化简,重载+、-、*、/运算符完成四则运算,重载“==”符号判断两个有理数是否相等。
时间: 2024-05-09 08:14:41 浏览: 263
好的,以下是一个简单的有理数类的定义:
```cpp
class RationalNumber {
private:
int numerator; // 分子
int denominator; // 分母
void simplify(); // 化简
public:
RationalNumber(int num = 0, int den = 1); // 构造函数
bool isValid() const; // 判断是否为合法有理数
friend RationalNumber operator+(const RationalNumber& r1, const RationalNumber& r2); // 重载加法运算符
friend RationalNumber operator-(const RationalNumber& r1, const RationalNumber& r2); // 重载减法运算符
friend RationalNumber operator*(const RationalNumber& r1, const RationalNumber& r2); // 重载乘法运算符
friend RationalNumber operator/(const RationalNumber& r1, const RationalNumber& r2); // 重载除法运算符
bool operator==(const RationalNumber& r) const; // 重载相等运算符
void print() const; // 打印有理数
};
```
其中,`numerator` 表示分子,`denominator` 表示分母。`simplify()` 函数用于化简有理数,`isValid()` 函数用于检测分母是否为0。四则运算符和相等运算符都是通过友元函数进行重载的。
以下是有理数类的函数实现:
```cpp
RationalNumber::RationalNumber(int num, int den) {
numerator = num;
denominator = den;
simplify();
}
bool RationalNumber::isValid() const {
return denominator != 0;
}
void RationalNumber::simplify() {
if (denominator == 0) {
return;
}
int gcd = std::__gcd(std::abs(numerator), denominator); // 计算分子分母的最大公约数
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) { // 如果分母为负数,则将分子分母都取相反数
numerator = -numerator;
denominator = -denominator;
}
}
RationalNumber operator+(const RationalNumber& r1, const RationalNumber& r2) {
RationalNumber result(r1.numerator * r2.denominator + r2.numerator * r1.denominator, r1.denominator * r2.denominator);
return result;
}
RationalNumber operator-(const RationalNumber& r1, const RationalNumber& r2) {
RationalNumber result(r1.numerator * r2.denominator - r2.numerator * r1.denominator, r1.denominator * r2.denominator);
return result;
}
RationalNumber operator*(const RationalNumber& r1, const RationalNumber& r2) {
RationalNumber result(r1.numerator * r2.numerator, r1.denominator * r2.denominator);
return result;
}
RationalNumber operator/(const RationalNumber& r1, const RationalNumber& r2) {
RationalNumber result(r1.numerator * r2.denominator, r1.denominator * r2.numerator);
return result;
}
bool RationalNumber::operator==(const RationalNumber& r) const {
return numerator == r.numerator && denominator == r.denominator;
}
void RationalNumber::print() const {
if (!isValid()) {
std::cout << "Invalid Rational Number" << std::endl;
} else if (denominator == 1) {
std::cout << numerator << std::endl; // 分母为1,只输出分子
} else {
std::cout << numerator << "/" << denominator << std::endl;
}
}
```
通过以上定义和实现,我们就可以愉快地使用有理数类进行四则运算了!
阅读全文