计一个类,用菜单选择用成员函数重载运算符或友元函数重载运算符,使对整型的运算符=、+、-、*、/ 适用于分数运算。要求: (1) 输出结果是最简分数(可以是带分数); (2) 分母为1,只输出分子。
时间: 2024-02-15 21:06:06 浏览: 77
以下是一个实现上述要求的分数类的示例代码:
```
#include <iostream>
using namespace std;
class Fraction {
private:
int numerator; // 分子
int denominator; // 分母
public:
Fraction() {
numerator = 0;
denominator = 1;
}
Fraction(int num, int den) {
numerator = num;
denominator = den;
simplify();
}
void simplify() {
int gcd = getGCD(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
int getGCD(int x, int y) {
if (y == 0) {
return x;
}
return getGCD(y, x % y);
}
friend Fraction operator+(const Fraction& f1, const Fraction& f2) {
int num = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
int den = f1.denominator * f2.denominator;
return Fraction(num, den);
}
friend Fraction operator-(const Fraction& f1, const Fraction& f2) {
int num = f1.numerator * f2.denominator - f2.numerator * f1.denominator;
int den = f1.denominator * f2.denominator;
return Fraction(num, den);
}
friend Fraction operator*(const Fraction& f1, const Fraction& f2) {
int num = f1.numerator * f2.numerator;
int den = f1.denominator * f2.denominator;
return Fraction(num, den);
}
friend Fraction operator/(const Fraction& f1, const Fraction& f2) {
int num = f1.numerator * f2.denominator;
int den = f1.denominator * f2.numerator;
return Fraction(num, den);
}
Fraction& operator=(const Fraction& other) {
numerator = other.numerator;
denominator = other.denominator;
return *this;
}
friend ostream& operator<<(ostream& os, const Fraction& f) {
if (f.denominator == 1) {
os << f.numerator;
} else if (abs(f.numerator) >= f.denominator) {
int integer = f.numerator / f.denominator;
int num = abs(f.numerator) % f.denominator;
if (f.numerator < 0) {
os << "-";
}
os << integer << " " << num << "/" << f.denominator;
} else {
os << f.numerator << "/" << f.denominator;
}
return os;
}
};
int main() {
Fraction f1(1, 3);
Fraction f2(2, 5);
Fraction f3 = f1 + f2;
cout << f3 << endl; // output: 11/15
f3 = f1 - f2;
cout << f3 << endl; // output: 1/15
f3 = f1 * f2;
cout << f3 << endl; // output: 2/15
f3 = f1 / f2;
cout << f3 << endl; // output: 5/6
return 0;
}
```
该示例代码中,Fraction 类重载了运算符+、-、*、/ 和=,并且还定义了一个友元函数重载运算符<<,用于输出 Fraction 类型的对象。在运算符重载函数中,需要注意将分数化简为最简分数,且要处理分母为1的情况和负数的情况。
阅读全文