(1)建立一个分数类。分数类的数据成员包括分子和分母,操作包括通分、比较、加、减、乘、除、求倒数、显示和输入。
时间: 2023-11-16 11:04:09 浏览: 116
以下是一个简单的分数类实现,包括了所要求的操作:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
class Fraction {
public:
Fraction(int num = 0, int den = 1) : numerator(num), denominator(den) {}
void normalize() {
int gcd = __gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
void common_denominator(Fraction &other) {
int lcm = denominator * other.denominator / __gcd(denominator, other.denominator);
numerator *= lcm / denominator;
other.numerator *= lcm / other.denominator;
denominator = other.denominator = lcm;
}
bool operator==(const Fraction &other) const {
return numerator == other.numerator && denominator == other.denominator;
}
bool operator<(const Fraction &other) const {
return numerator * other.denominator < other.numerator * denominator;
}
Fraction operator+(const Fraction &other) const {
Fraction result = *this;
result.common_denominator((Fraction &) other);
result.numerator += other.numerator;
result.normalize();
return result;
}
Fraction operator-(const Fraction &other) const {
Fraction result = *this;
result.common_denominator((Fraction &) other);
result.numerator -= other.numerator;
result.normalize();
return result;
}
Fraction operator*(const Fraction &other) const {
Fraction result = *this;
result.numerator *= other.numerator;
result.denominator *= other.denominator;
result.normalize();
return result;
}
Fraction operator/(const Fraction &other) const {
Fraction result = *this;
result.numerator *= other.denominator;
result.denominator *= other.numerator;
result.normalize();
return result;
}
Fraction reciprocal() const {
Fraction result(denominator, numerator);
result.normalize();
return result;
}
void display() const {
cout << numerator << "/" << denominator;
}
void input() {
cout << "Enter numerator and denominator: ";
cin >> numerator >> denominator;
normalize();
}
private:
int numerator, denominator;
};
```
这个类里面,我们定义了构造函数,通分函数,归一化函数,比较运算符,加减乘除运算符,求倒数函数,显示函数和输入函数。其中,通分函数用于将两个分数的分母变为最小公倍数,以便进行加减运算。归一化函数用于将分数约分为最简形式。比较运算符用于比较两个分数的大小关系。加减乘除运算符则实现了对应的数学运算。求倒数函数用于求出分数的倒数。显示函数用于将分数以 x/y 的形式输出。输入函数用于从键盘输入分数的值。
阅读全文