c++写Rational类
时间: 2024-03-15 22:44:26 浏览: 149
有理数_有理数类Rational_
下面是一个简单的C++实现Rational类的代码,包括了常见的运算符重载和一些基本的操作:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Rational {
public:
Rational(int numerator = 0, int denominator = 1) :
numerator_(numerator), denominator_(denominator) {}
Rational(const Rational& other) :
numerator_(other.numerator_), denominator_(other.denominator_) {}
// 加法运算符重载
Rational operator+(const Rational& other) const {
int new_numerator = numerator_ * other.denominator_ + other.numerator_ * denominator_;
int new_denominator = denominator_ * other.denominator_;
return Rational(new_numerator, new_denominator);
}
// 减法运算符重载
Rational operator-(const Rational& other) const {
int new_numerator = numerator_ * other.denominator_ - other.numerator_ * denominator_;
int new_denominator = denominator_ * other.denominator_;
return Rational(new_numerator, new_denominator);
}
// 乘法运算符重载
Rational operator*(const Rational& other) const {
int new_numerator = numerator_ * other.numerator_;
int new_denominator = denominator_ * other.denominator_;
return Rational(new_numerator, new_denominator);
}
// 除法运算符重载
Rational operator/(const Rational& other) const {
int new_numerator = numerator_ * other.denominator_;
int new_denominator = denominator_ * other.numerator_;
return Rational(new_numerator, new_denominator);
}
// 等于运算符重载
bool operator==(const Rational& other) const {
return numerator_ * other.denominator_ == denominator_ * other.numerator_;
}
// 不等于运算符重载
bool operator!=(const Rational& other) const {
return !(*this == other);
}
// 大于运算符重载
bool operator>(const Rational& other) const {
return numerator_ * other.denominator_ > denominator_ * other.numerator_;
}
// 小于运算符重载
bool operator<(const Rational& other) const {
return numerator_ * other.denominator_ < denominator_ * other.numerator_;
}
// 大于等于运算符重载
bool operator>=(const Rational& other) const {
return !(*this < other);
}
// 小于等于运算符重载
bool operator<=(const Rational& other) const {
return !(*this > other);
}
// 转换为double类型
double to_double() const {
return (double)numerator_ / denominator_;
}
// 约分操作
void reduce() {
int gcd = abs(__gcd(numerator_, denominator_));
numerator_ /= gcd;
denominator_ /= gcd;
}
// 转换为字符串形式
string to_string() const {
reduce();
if (denominator_ == 1) {
return std::to_string(numerator_);
} else {
return std::to_string(numerator_) + "/" + std::to_string(denominator_);
}
}
// 输入流运算符重载
friend istream& operator>>(istream& in, Rational& r) {
in >> r.numerator_ >> r.denominator_;
return in;
}
// 输出流运算符重载
friend ostream& operator<<(ostream& out, const Rational& r) {
out << r.to_string();
return out;
}
private:
int numerator_; // 分子
int denominator_; // 分母
};
```
上述代码中,我们定义了一个Rational类,它包含了两个成员变量numerator和denominator,分别表示有理数的分子和分母。我们还定义了一些基本的运算符重载函数,包括加、减、乘、除、等于、不等于、大于、小于、大于等于和小于等于运算符。Rational类还实现了一些基本的操作,如转换为double类型、约分操作和转换为字符串形式等。其中,我们使用了C++11标准中的__gcd函数来求最大公约数。最后,我们还实现了输入输出流运算符重载函数,使得我们可以方便地使用cin和cout来输入输出Rational类型的数据。
阅读全文