forked from AufarLIRS/CPP-2019-2020-HW4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rational.cpp
116 lines (96 loc) · 2.36 KB
/
rational.cpp
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
116
#include "rational.h"
Rational::Rational(int numerator, int denominator = 1)
{
auto gcd = getGCD(numerator, denominator);
this->numerator_ = numerator / gcd;
this->denominator_ = denominator / gcd;
}
Rational::operator double() const
{
return double(numerator_) / denominator_;
}
int Rational::getNumerator() const
{
return numerator_;
}
int Rational::getDenominator() const
{
return denominator_;
}
int Rational::getGCD(int x, int y)
{
int t;
while (y != 0)
{
t = y;
y = x % y;
x = t;
}
return x;
}
void Rational::print(Rational r)
{
std::cout << r.getNumerator() << "/" << r.getDenominator();
}
Rational operator+(Rational const& r1, Rational const& r2)
{
return Rational(r1.getNumerator() * r2.getDenominator() + r2.getNumerator() * r1.getDenominator(),
r1.getDenominator() * r2.getDenominator());
}
Rational operator-(Rational const& r1, Rational const& r2)
{
return Rational(r1.getNumerator() * r2.getDenominator() - r2.getNumerator() * r1.getDenominator(),
r1.getDenominator() * r2.getDenominator());
}
Rational operator*(Rational const& r1, Rational const& r2)
{
return Rational(r1.getNumerator() * r2.getNumerator(), r1.getDenominator() * r2.getDenominator());
}
Rational operator/(Rational const& r1, Rational const& r2)
{
return Rational(r1.getNumerator() * r2.getDenominator(), r1.getDenominator() * r2.getNumerator());
}
Rational& Rational::operator++(int)
{
numerator_ += denominator_;
return *this;
}
Rational& Rational::operator++()
{
numerator_ += denominator_;
return *this;
}
Rational& Rational::operator--(int)
{
numerator_ -= denominator_;
return *this;
}
Rational& Rational::operator--()
{
numerator_ -= denominator_;
return *this;
}
bool operator>(Rational const& r1, Rational const& r2)
{
return r1.getNumerator() * r2.getDenominator() > r1.getDenominator() * r2.getNumerator();
}
bool operator<(Rational const& r1, Rational const& r2)
{
return !(r1 > r2);
}
bool operator==(Rational const& r1, Rational const& r2)
{
return (r1.getNumerator() == r2.getNumerator() && r1.getDenominator() == r2.getDenominator());
}
bool operator!=(Rational const& r1, Rational const& r2)
{
return !(r1 == r2);
}
bool operator<=(Rational const& r1, Rational const& r2)
{
return r1 == r2 || r1 < r2;
}
bool operator>=(Rational const& r1, Rational const& r2)
{
return r1 == r2 || r1 > r2;
}