试、打印点的信息和计算结果。 (3)写分数类的定义,要求在分数类中提供最简化约分、两个分数求和、求差、求积、求除的成员函数,并在main函数里进行测试、打印分数及计算结果。
时间: 2023-07-10 10:39:37 浏览: 91
以下是分数类的定义:
```c++
#include <iostream>
class Fraction {
private:
int numerator;
int denominator;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public:
Fraction(int _numerator, int _denominator) : numerator(_numerator), denominator(_denominator) {
int divisor = gcd(numerator, denominator);
numerator /= divisor;
denominator /= divisor;
}
int getNumerator() const {
return numerator;
}
int getDenominator() const {
return denominator;
}
Fraction operator+(const Fraction& other) const {
int num = numerator * other.denominator + other.numerator * denominator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator-(const Fraction& other) const {
int num = numerator * other.denominator - other.numerator * denominator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator*(const Fraction& other) const {
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return Fraction(num, den);
}
Fraction operator/(const Fraction& other) const {
int num = numerator * other.denominator;
int den = denominator * other.numerator;
return Fraction(num, den);
}
};
int main() {
Fraction f1(2, 3);
Fraction f2(3, 4);
std::cout << "f1: " << f1.getNumerator() << "/" << f1.getDenominator() << std::endl;
std::cout << "f2: " << f2.getNumerator() << "/" << f2.getDenominator() << std::endl;
Fraction sum = f1 + f2;
std::cout << "Sum: " << sum.getNumerator() << "/" << sum.getDenominator() << std::endl;
Fraction diff = f1 - f2;
std::cout << "Difference: " << diff.getNumerator() << "/" << diff.getDenominator() << std::endl;
Fraction prod = f1 * f2;
std::cout << "Product: " << prod.getNumerator() << "/" << prod.getDenominator() << std::endl;
Fraction quotient = f1 / f2;
std::cout << "Quotient: " << quotient.getNumerator() << "/" << quotient.getDenominator() << std::endl;
return 0;
}
```
在 main 函数中,我们首先创建了两个分数 f1 和 f2,分别代表 2/3 和 3/4。
然后,我们分别调用了每个分数的 getNumerator 和 getDenominator 函数,来输出它们的分子和分母。
接下来,我们分别调用了四个运算符重载函数,来计算两个分数的和、差、积和商,并分别输出结果。
最后,我们在主函数中返回 0,表示程序运行成功结束。
阅读全文