有理数的加减乘除运算c++
时间: 2023-11-27 22:51:03 浏览: 102
有理数加减乘除
以下是 C++ 中有理数的加减乘除运算示例代码:
```c++
#include <iostream>
using namespace std;
class Rational {
private:
int numerator; // 分子
int denominator; // 分母
public:
// 构造函数
Rational(int numerator = 0, int denominator = 1) {
if (denominator == 0) {
cout << "Error: denominator cannot be 0!" << endl;
exit(1);
}
if (numerator == 0) {
this->numerator = 0;
this->denominator = 1;
} else {
int gcd = getGCD(numerator, denominator);
this->numerator = numerator / gcd;
this->denominator = denominator / gcd;
if (this->denominator < 0) {
this->numerator = -this->numerator;
this->denominator = -this->denominator;
}
}
}
// 获取最大公约数
int getGCD(int a, int b) {
if (b == 0) return a;
return getGCD(b, a % b);
}
// 加法运算
Rational operator+(Rational const& r) {
int newNumerator = this->numerator * r.denominator + r.numerator * this->denominator;
int newDenominator = this->denominator * r.denominator;
return Rational(newNumerator, newDenominator);
}
// 减法运算
Rational operator-(Rational const& r) {
int newNumerator = this->numerator * r.denominator - r.numerator * this->denominator;
int newDenominator = this->denominator * r.denominator;
return Rational(newNumerator, newDenominator);
}
// 乘法运算
Rational operator*(Rational const& r) {
int newNumerator = this->numerator * r.numerator;
int newDenominator = this->denominator * r.denominator;
return Rational(newNumerator, newDenominator);
}
// 除法运算
Rational operator/(Rational const& r) {
if (r.numerator == 0) {
cout << "Error: division by 0!" << endl;
exit(1);
}
int newNumerator = this->numerator * r.denominator;
int newDenominator = this->denominator * r.numerator;
return Rational(newNumerator, newDenominator);
}
// 输出有理数
friend ostream& operator<<(ostream& os, Rational const& r) {
if (r.denominator == 1) {
os << r.numerator;
} else {
os << r.numerator << "/" << r.denominator;
}
return os;
}
};
int main() {
Rational a(1, 2);
Rational b(3, 4);
Rational c = a + b;
Rational d = a - b;
Rational e = a * b;
Rational f = a / b;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << c << endl;
cout << "a - b = " << d << endl;
cout << "a * b = " << e << endl;
cout << "a / b = " << f << endl;
return 0;
}
```
输出结果:
```
a = 1/2
b = 3/4
a + b = 5/4
a - b = -1/4
a * b = 3/8
a / b = 2/3
```
阅读全文