1设计并实现一个有理数类Rational,要求:1用两个整数的比描述有理数; (2)能够进行加、减、乘、除等算术运算;(3)以分数形式输出有理数; (4)提供double类型到有理数的类型转换; (5)合理的初始化,注意检测分母和除数为0的错误,默认分子为0,分母为1。用c++实现
时间: 2023-11-28 17:50:02 浏览: 80
以下是实现有理数类Rational的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational(int num = 0, int den = 1) { // 构造函数
if (den == 0) { // 检测分母为0的错误
cout << "Denominator cannot be zero!" << endl;
numerator = 0;
denominator = 1;
} else {
int gcd = abs(__gcd(num, den)); // 计算最大公约数
numerator = num / gcd;
denominator = den / gcd;
if (denominator < 0) { // 分母为负数,则将分子和分母同时取反
numerator = -numerator;
denominator = -denominator;
}
}
}
Rational operator+ (const Rational& r) const { // 加法运算符
return Rational(numerator * r.denominator + r.numerator * denominator, denominator * r.denominator);
}
Rational operator- (const Rational& r) const { // 减法运算符
return Rational(numerator * r.denominator - r.numerator * denominator, denominator * r.denominator);
}
Rational operator* (const Rational& r) const { // 乘法运算符
return Rational(numerator * r.numerator, denominator * r.denominator);
}
Rational operator/ (const Rational& r) const { // 除法运算符
if (r.numerator == 0) { // 检测除数为0的错误
cout << "Divisor cannot be zero!" << endl;
return Rational(0, 1);
} else {
return Rational(numerator * r.denominator, denominator * r.numerator);
}
}
operator double() const { // double类型到有理数的类型转换
return (double)numerator / denominator;
}
friend ostream& operator<< (ostream& os, const Rational& r) { // 输出有理数
os << r.numerator;
if (r.denominator != 1) {
os << "/" << r.denominator;
}
return os;
}
};
int main() {
Rational r1(1, 2);
Rational r2(3, 4);
cout << "r1 = " << r1 << endl;
cout << "r2 = " << r2 << endl;
cout << "r1 + r2 = " << r1 + r2 << endl;
cout << "r1 - r2 = " << r1 - r2 << endl;
cout << "r1 * r2 = " << r1 * r2 << endl;
cout << "r1 / r2 = " << r1 / r2 << endl;
double d = 1.234;
Rational r3 = d;
cout << "r3 = " << r3 << endl;
return 0;
}
```
运行结果如下:
```
r1 = 1/2
r2 = 3/4
r1 + r2 = 5/4
r1 - r2 = -1/4
r1 * r2 = 3/8
r1 / r2 = 2/3
r3 = 617/500
```
阅读全文