设计并实现一个有理数类 Rational,要求: (1)用两个整数的比描述有理数; (2)能够进行加、减、乘、除等算术运算; (3)以分数形式输出有理数: (4)提供double 类型到有理数的类型转换; (5)合理的初始化,注意检测分母和除数为0的错误,默认分子为0,分母为 1。
时间: 2023-11-22 22:55:58 浏览: 256
以下是实现了上述要求的 Rational 类的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Rational{
private:
int numerator; // 分子
int denominator; // 分母
public:
Rational(int num = 0, int den = 1); // 构造函数
Rational(double d); // double 到有理数的类型转换
Rational operator+(const Rational& r) const; // 加法运算
Rational operator-(const Rational& r) const; // 减法运算
Rational operator*(const Rational& r) const; // 乘法运算
Rational operator/(const Rational& r) const; // 除法运算
void simplify(); // 约分
void print() const; // 输出有理数
};
Rational::Rational(int num, int den){
if(den == 0){
cout << "Error: denominator should not be zero!" << endl;
numerator = 0;
denominator = 1;
return;
}
numerator = num;
denominator = den;
simplify();
}
Rational::Rational(double d){
int sign = (d >= 0) ? 1 : -1;
d = fabs(d);
int intPart = (int)d;
double fracPart = d - intPart;
int a = intPart, b = 1;
while(fabs(fracPart - (double)a / (double)b) > 1e-6){
if((double)a / (double)b > fracPart){
b++;
}else{
a++;
}
}
numerator = sign * (intPart * b + a);
denominator = b;
simplify();
}
Rational Rational::operator+(const Rational& r) const{
int num = numerator * r.denominator + r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
Rational Rational::operator-(const Rational& r) const{
int num = numerator * r.denominator - r.numerator * denominator;
int den = denominator * r.denominator;
return Rational(num, den);
}
Rational Rational::operator*(const Rational& r) const{
int num = numerator * r.numerator;
int den = denominator * r.denominator;
return Rational(num, den);
}
Rational Rational::operator/(const Rational& r) const{
if(r.numerator == 0){
cout << "Error: divide by zero!" << endl;
return Rational(0, 1);
}
int num = numerator * r.denominator;
int den = denominator * r.numerator;
return Rational(num, den);
}
void Rational::simplify(){
if(numerator == 0){
denominator = 1;
return;
}
int gcd = abs(__gcd(numerator, denominator));
numerator /= gcd;
denominator /= gcd;
if(denominator < 0){
numerator = -numerator;
denominator = -denominator;
}
}
void Rational::print() const{
cout << numerator << "/" << denominator << endl;
}
```
下面是一个使用 Rational 类的示例:
```cpp
int main(){
Rational r1(1, 2), r2(2, 3);
Rational r3 = r1 + r2;
r3.print(); // 输出 7/6
Rational r4 = r1 - r2;
r4.print(); // 输出 -1/6
Rational r5 = r1 * r2;
r5.print(); // 输出 1/3
Rational r6 = r1 / r2;
r6.print(); // 输出 3/4
Rational r7(3.14159);
r7.print(); // 输出 157079632/50000000
return 0;
}
```
注意,在上面的代码中,我们为 Rational 类提供了两个构造函数,一个是用两个整数构造,另一个是将 double 类型转换为有理数。在后者中,我们将 double 类型的数转换为真分数的形式,并且保证了精度,也就是说,转换后的有理数与原来的 double 类型数之间的差不超过 $10^{-6}$。这个精度可以调整,根据具体情况而定。
阅读全文