c++编写有理数(即分数,包括整数类型的分子和分母)类,并进行运算符重载,编写运算符“+”、 “-”、 “*”、 “/”、 “>>” 、“<<”的重载函数,在主函数的函数体内中实现使用运算符直接进行有理数对象的加、减、乘、除运算。
时间: 2023-11-05 21:58:35 浏览: 108
c++ 编写的 有理数类
以下是一份实现有理数类的示例代码:
```c
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
class Rational {
public:
Rational(int num, int den) {
int d = gcd(num, den);
numerator = num / d;
denominator = den / d;
}
Rational(int num) {
numerator = num;
denominator = 1;
}
Rational() {
numerator = 0;
denominator = 1;
}
Rational operator+(const Rational& other) const {
int num = numerator * other.denominator + denominator * other.numerator;
int den = denominator * other.denominator;
return Rational(num, den);
}
Rational operator-(const Rational& other) const {
int num = numerator * other.denominator - denominator * other.numerator;
int den = denominator * other.denominator;
return Rational(num, den);
}
Rational operator*(const Rational& other) const {
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Rational(num, den);
}
Rational operator/(const Rational& other) const {
int num = numerator * other.denominator;
int den = denominator * other.numerator;
return Rational(num, den);
}
friend ostream& operator<<(ostream& os, const Rational& r) {
os << r.numerator;
if (r.denominator != 1) {
os << '/' << r.denominator;
}
return os;
}
friend istream& operator>>(istream& is, Rational& r) {
int num, den;
char c;
is >> num >> c >> den;
r = Rational(num, den);
return is;
}
private:
int numerator;
int denominator;
};
int main() {
Rational a(1, 2);
Rational b(3, 4);
Rational c = a + b;
cout << a << " + " << b << " = " << c << endl;
c = a - b;
cout << a << " - " << b << " = " << c << endl;
c = a * b;
cout << a << " * " << b << " = " << c << endl;
c = a / b;
cout << a << " / " << b << " = " << c << endl;
Rational d;
cout << "Input a rational number: ";
cin >> d;
cout << "The number you input is: " << d << endl;
return 0;
}
```
上述代码中,我们定义了一个有理数类`Rational`,并实现了加、减、乘、除等运算符的重载函数。在主函数中,我们创建了两个有理数对象`a`和`b`,并使用运算符直接对它们进行加、减、乘、除运算,并输出结果。同时,我们还重载了输入和输出运算符`>>`和`<<`,以方便输入和输出有理数对象。
运行上述代码,输出结果如下:
```
1/2 + 3/4 = 5/4
1/2 - 3/4 = -1/4
1/2 * 3/4 = 3/8
1/2 / 3/4 = 2/3
Input a rational number: 7/8
The number you input is: 7/8
```
阅读全文