C++运算符重载实现有理数运算
程序员文章站
2022-07-10 19:11:02
...
C++运算符重载实现有理数运算
实现有理数的加减乘除
//1/8 + 7/8 = 1
//拆分成分子分母
//利用运算符重载实现有理数之间的运算
1 #include <iostream>
2 #include <stdlib.h>
3
4 class RationalNumber
5 {
6 public:
7 RationalNumber();
8 RationalNumber(int x, int y);
9 RationalNumber operator+(RationalNumber rhs);
10 RationalNumber operator-(RationalNumber rhs);
11 RationalNumber operator*(RationalNumber rhs);
12 RationalNumber operator/(RationalNumber rhs);
13 void print();
14 private:
15 int mole;
16 int denom;
17 void simplify();
18 };
19
20 RationalNumber::RationalNumber()
21 {
22 mole = 0;
23 denom = 0;
24 simplify();
25 }
26
27 RationalNumber::RationalNumber(int x, int y)
28 {
29 mole = x;
30 denom = y;
31 simplify();
32 }
33
34 void RationalNumber::simplify()
35 {
36 if (denom < 0)
37 {
38 denom = -denom;
39 mole = -mole;
40 }
41 int x = abs(mole);
42 int y = abs(denom);
43
44 while (y > 0)
45 {
46 int t = x % y;
47 x = y;
48 y = t;
49 }
50 mole /= x;
51 denom /= x;
52 }
53
54 RationalNumber RationalNumber::operator+(RationalNumber rhs)
55 {
56 return RationalNumber(mole * rhs.denom + denom * rhs.mole, denom*rhs.denom);
57 }
58
59 RationalNumber RationalNumber::operator-(RationalNumber rhs)
60 {
61 rhs.mole = -rhs.mole;
62 return operator+(rhs);
63 }
64
65 RationalNumber RationalNumber::operator *(RationalNumber rhs)
66 {
67 return RationalNumber(mole * rhs.mole, denom * rhs.denom);
68 }
69
70 RationalNumber RationalNumber::operator/(RationalNumber rhs)
71 {
72 return RationalNumber(mole *rhs.denom, denom * rhs.mole);
73 }
74
75 void RationalNumber::print()
76 {
77 if(mole % denom == 0)
78 {
79 std::cout << mole / denom;
80 }
81 else
82 {
83 std::cout << mole << "/" << denom;
84 }
85 }
86
87 int main ()
88 {
89 RationalNumber f1(1,12);
90 RationalNumber f2(3,12);
91 RationalNumber f3 = f1 + f2;
92 f1.print();
93 std::cout << " + ";
94 f2.print() ;
95 std::cout << " = ";
96 f3.print();
97 std::cout << std::endl;
98
99 f3 = f1 - f2;
100 f1.print();
101 std::cout << " - ";
102 f2.print() ;
103 std::cout << " = ";
104 f3.print();
105 std::cout << std::endl;
106
107 f3 = f1 * f2;
108 f1.print();
109 std::cout << " * ";
110 f2.print() ;
111 std::cout << " = ";
112 f3.print();
113 std::cout << std::endl;
114
115 f3 = f1 / f2;
116 f1.print();
117 std::cout << " / ";
118 f2.print() ;
119 std::cout << " = ";
120 f3.print();
121 std::cout << std::endl;
122
123 return 0;
124 }
结果
下一篇: Java基础语法之类和对象理解