11设计并实现一个有理数类Rational,要求:1用两个整数的比描述有理数; (2)能够进行加、减、乘、除等算术运算;(3)以分数形式输出有理数; (4)提供double类型到有理数的类型转换; (5)合理的初始化,注意检测分母和除数为0的错误,默认分子为0,分母为1。用c++编写
时间: 2023-11-28 11:50:18 浏览: 161
以下是实现有理数类Rational的代码:
```c++
#include <iostream>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
// 构造函数
Rational(int num = 0, int den = 1) {
if (den == 0) {
cout << "Error: the denominator can't be zero!" << endl;
numerator = 0;
denominator = 1;
} else {
numerator = num;
denominator = den;
reduce(); // 约分
}
}
// 获取分子
int getNumerator() const {
return numerator;
}
// 获取分母
int getDenominator() const {
return denominator;
}
// 加法
Rational operator+(const Rational& r) const {
int num = numerator * r.denominator + r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 减法
Rational operator-(const Rational& r) const {
int num = numerator * r.denominator - r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 乘法
Rational operator*(const Rational& r) const {
int num = numerator * r.numerator;
int den = denominator * r.denominator;
return Rational(num, den);
}
// 除法
Rational operator/(const Rational& r) const {
int num = numerator * r.denominator;
int den = denominator * r.numerator;
return Rational(num, den);
}
// 转double类型
operator double() const {
return (double)numerator / denominator;
}
// 约分
void reduce() {
if (numerator == 0) {
denominator = 1;
} else {
int gcd = getGCD(abs(numerator), denominator);
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
}
// 打印分数形式
void print() const {
cout << numerator << "/" << denominator << endl;
}
private:
// 求最大公约数
int getGCD(int a, int b) {
if (b == 0) {
return a;
} else {
return getGCD(b, a % b);
}
}
};
```
用以下代码进行测试:
```c++
int main() {
Rational r1(2, 3);
Rational r2(3, 4);
Rational r3;
r3 = r1 + r2;
r3.print(); // 打印结果为17/12
r3 = r1 - r2;
r3.print(); // 打印结果为-1/12
r3 = r1 * r2;
r3.print(); // 打印结果为1/2
r3 = r1 / r2;
r3.print(); // 打印结果为8/9
double d = (double)r1;
cout << d << endl; // 输出结果为0.666667
return 0;
}
```
阅读全文