设计并实现一个有理数类Rational,要求: (1)用两个整数的比描述有理数; (2)能够进行加,减,乘,除等算术运算; (3)以分数形式输出有理数; (4)提供double类型到有理数的类型转换; (5)合理的初始化,注意检测分母和除数为0的错误,默认分子为0,分母为1; 编写测试程序。
时间: 2023-11-28 17:50:24 浏览: 89
以下是实现Rational类的代码:
```cpp
#include <iostream>
using namespace std;
class Rational {
public:
Rational(int numerator = 0, int denominator = 1) {
if (denominator == 0) {
cout << "Error: denominator cannot be zero!" << endl;
num = 0;
den = 1;
} else {
int gcd_num_den = gcd(numerator, denominator);
num = numerator / gcd_num_den;
den = denominator / gcd_num_den;
if (den < 0) {
num = -num;
den = -den;
}
}
}
int get_num() const {
return num;
}
int get_den() const {
return den;
}
double to_double() const {
return static_cast<double>(num) / den;
}
void print() const {
cout << num << "/" << den;
}
Rational operator+ (const Rational& b) const {
int new_num = num * b.den + b.num * den;
int new_den = den * b.den;
return Rational(new_num, new_den);
}
Rational operator- (const Rational& b) const {
int new_num = num * b.den - b.num * den;
int new_den = den * b.den;
return Rational(new_num, new_den);
}
Rational operator* (const Rational& b) const {
int new_num = num * b.num;
int new_den = den * b.den;
return Rational(new_num, new_den);
}
Rational operator/ (const Rational& b) const {
int new_num = num * b.den;
int new_den = den * b.num;
return Rational(new_num, new_den);
}
private:
int num;
int den;
int gcd(int a, int b) const {
if (b == 0) return a;
else return gcd(b, a % b);
}
};
int main() {
Rational a(2, 3), b(3, 4);
Rational c = a + b;
c.print(); // 输出 17/12
cout << endl;
c = a - b;
c.print(); // 输出 -1/12
cout << endl;
c = a * b;
c.print(); // 输出 1/2
cout << endl;
c = a / b;
c.print(); // 输出 8/9
cout << endl;
cout << c.to_double() << endl; // 输出 0.888889
Rational d(1, 0); // 输出错误信息:"Error: denominator cannot be zero!"
d.print(); // 输出 0/1
cout << endl;
return 0;
}
```
输出结果:
```
17/12
-1/12
1/2
8/9
0.888889
Error: denominator cannot be zero!
0/1
```
需要注意的是,为了避免分母为零的错误,我们在构造函数中进行了检查,并且默认分子为0,分母为1。在实际使用中,可以根据需要进行修改。
阅读全文