设计并实现一个有理数类Rational,要求: (1)用两个整数的比描述有理数; (2)能够进行加、减、乘、除等算术运算; (3)以分数形式输出有理数; (4)提供double类型到有理数的类型转换; (5)合理的初始化,注意检测分母和除数为0的错误,默认分子为0,分母为1。
时间: 2023-11-28 10:49:49 浏览: 84
以下是实现了上述要求的Rational类的代码:
```cpp
#include <iostream>
#include <cstdlib>
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational(int num = 0, int den = 1) {
if (den == 0) {
std::cerr << "Error: denominator cannot be zero!" << std::endl;
exit(EXIT_FAILURE);
}
numerator = num;
denominator = den;
simplify();
}
int getNumerator() const {
return numerator;
}
int getDenominator() const {
return denominator;
}
Rational operator+(const Rational& r) const {
Rational result;
result.numerator = numerator * r.denominator + r.numerator * denominator;
result.denominator = denominator * r.denominator;
result.simplify();
return result;
}
Rational operator-(const Rational& r) const {
Rational result;
result.numerator = numerator * r.denominator - r.numerator * denominator;
result.denominator = denominator * r.denominator;
result.simplify();
return result;
}
Rational operator*(const Rational& r) const {
Rational result;
result.numerator = numerator * r.numerator;
result.denominator = denominator * r.denominator;
result.simplify();
return result;
}
Rational operator/(const Rational& r) const {
if (r.numerator == 0) {
std::cerr << "Error: division by zero!" << std::endl;
exit(EXIT_FAILURE);
}
Rational result;
result.numerator = numerator * r.denominator;
result.denominator = denominator * r.numerator;
result.simplify();
return result;
}
double toDouble() const {
return (double)numerator / (double)denominator;
}
void print() const {
std::cout << numerator << "/" << denominator << std::endl;
}
private:
// 约分
void simplify() {
if (numerator == 0) {
denominator = 1;
return;
}
// 将分子、分母约分为最简形式
int gcdValue = gcd(numerator, denominator);
numerator /= gcdValue;
denominator /= gcdValue;
// 如果分母为负数,则将分子、分母都变为相反数
if (denominator < 0) {
numerator *= -1;
denominator *= -1;
}
}
// 计算最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
};
int main() {
Rational r1(2, 3);
Rational r2(3, 4);
Rational sum = r1 + r2;
Rational difference = r1 - r2;
Rational product = r1 * r2;
Rational quotient = r1 / r2;
std::cout << "r1 = ";
r1.print();
std::cout << "r2 = ";
r2.print();
std::cout << "r1 + r2 = ";
sum.print();
std::cout << "r1 - r2 = ";
difference.print();
std::cout << "r1 * r2 = ";
product.print();
std::cout << "r1 / r2 = ";
quotient.print();
std::cout << "r1 as double: " << r1.toDouble() << std::endl;
std::cout << "r2 as double: " << r2.toDouble() << std::endl;
return 0;
}
```
输出结果如下:
```
r1 = 2/3
r2 = 3/4
r1 + r2 = 17/12
r1 - r2 = -1/12
r1 * r2 = 1/2
r1 / r2 = 8/9
r1 as double: 0.666667
r2 as double: 0.75
```
阅读全文