帮我写一个程序1. 定义一个有理数类Rational,包含分子和分母两个属性,为其重载四则运算和输入输出流,以使用cin和cout对Rational的对象进行输入和输出。
时间: 2024-05-12 14:16:41 浏览: 147
编写一个用输入和输出流运算符进行的输入和输出的程序。从键盘输入两个数,分别对两个数进行加,减,乘和除的运算。
好的,下面是代码实现:
```cpp
#include <iostream>
using namespace std;
class Rational {
public:
Rational(int num = 0, int den = 1) : numerator(num), denominator(den) {}
friend istream& operator>>(istream& in, Rational& r) {
char slash;
in >> r.numerator >> slash >> r.denominator;
return in;
}
friend ostream& operator<<(ostream& out, const Rational& r) {
out << r.numerator << '/' << r.denominator;
return out;
}
friend Rational operator+(const Rational& a, const Rational& b) {
return Rational(a.numerator*b.denominator + a.denominator*b.numerator, a.denominator*b.denominator);
}
friend Rational operator-(const Rational& a, const Rational& b) {
return Rational(a.numerator*b.denominator - a.denominator*b.numerator, a.denominator*b.denominator);
}
friend Rational operator*(const Rational& a, const Rational& b) {
return Rational(a.numerator*b.numerator, a.denominator*b.denominator);
}
friend Rational operator/(const Rational& a, const Rational& b) {
return Rational(a.numerator*b.denominator, a.denominator*b.numerator);
}
private:
int numerator;
int denominator;
};
int main() {
Rational a, b;
cout << "Please enter two rational numbers (format like 1/2):" << endl;
cin >> a >> b;
cout << a << " + " << b << " = " << a+b << endl;
cout << a << " - " << b << " = " << a-b << endl;
cout << a << " * " << b << " = " << a*b << endl;
cout << a << " / " << b << " = " << a/b << endl;
return 0;
}
```
阅读全文