C++重载运算符实现分数加减乘除

时间:2022-03-24 18:25:15

本文实例为大家分享了C++重载运算符实现分数加减乘除的具体代码,供大家参考,具体内容如下

实现结果如下图所示:

C++重载运算符实现分数加减乘除

代码如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
 
using namespace std;
 
class Rational {
public:
 Rational operator+(Rational rhs);
 Rational operator-(Rational rhs);
 Rational operator*(Rational rhs);
 Rational operator/(Rational rhs);
 Rational(int num, int denom);
 
private:
 void normalize(); //负责对分数做化简工作
 
 int numerator;//分子
 int denominator;//分母
 
 friend std::ostream& operator<<(ostream& os, Rational f);
};
 
Rational::Rational(int num, int denom) {
 numerator = num;
 denominator = denom;
 
 normalize();
}
 
//只允许分子为负数,若分母为负数则把负数挪到分子部分
//利用欧几里得算法将分数简化
void Rational::normalize() {
 if (denominator < 0) {
  numerator = -numerator;
  denominator = -denominator;
 }
 
 //欧几里得算法
 int a = abs(numerator);
 int b = abs(denominator);
 
 //求出最大公约数,a
 //eg: a=12,b=9.
 //t=3 a=9 b=3
 //t=0 a=3 b=0
 while (b > 0) {
  int t = a % b;//t为余数
  a = b; //a取除数
  b = t; //b取余数
 }
 
 //分子、分母分别处以最大公约数
 numerator /= a;
 denominator /= a;
}
 
//重载运算符函数是类的成员函数
//分数是先通分再加减
// a*d+b*c / b*d
Rational Rational::operator+(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*d+b*c,b*d);
}
Rational Rational::operator-(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*d - b*c, b*d);
 
 /*
 **这里有个偷懒的写法
 rhs.numerator = -rhs.numerator;
 return operator+(rhs);
 */
}
Rational Rational::operator*(Rational rhs) {
 int a = numerator;
 int b = denominator;
 int c = rhs.numerator;
 int d = rhs.denominator;
 
 return Rational(a*c, b*d);
}
Rational Rational::operator/(Rational rhs) {
 int t = rhs.denominator;
 rhs.denominator = rhs.numerator;
 rhs.numerator = t;
 
 return operator*(rhs);
}
//该函数是友元函数,因此不用加空间域名
ostream& operator<<(ostream& os, Rational f);
 
int main() {
 Rational r1(4, 18);
 Rational r2(14, 18);
 
 cout << r1 << " + " << r2 << " = " << (r1 + r2) << endl;
 cout << r1 << " - " << r2 << " = " << (r1 - r2) << endl;
 cout << r1 << " * " << r2 << " = " << (r1 * r2) << endl;
 cout << r1 << " / " << r2 << " = " << (r1 / r2) << endl;
 
 system("pause");
 return 0;
}
 
ostream& operator<<(ostream& os, Rational f) {
 os << f.numerator << "/" << f.denominator;
 return os;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Quellaaa/article/details/80177341