This repository was archived by the owner on Aug 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_1_Rational_interface.cpp
More file actions
92 lines (79 loc) · 1.97 KB
/
09_1_Rational_interface.cpp
File metadata and controls
92 lines (79 loc) · 1.97 KB
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
#include <iostream>
#include <numeric>
using namespace std;
class Rational {
public:
Rational() {
num = 0;
denum = 1;
}
Rational(int numerator, int denominator) {
int div = gcd(numerator, denominator);
if (numerator < 0 && denominator < 0) {
denum = abs(denominator) / div;
num = abs(numerator) / div;
} else if (denominator < 0) {
denum = abs(denominator) / div;
num = numerator / div;
num = -num;
} else {
denum = denominator / div;
num = numerator / div;
}
}
int Numerator() const {
return num;
}
int Denominator() const {
return denum;
}
private:
int num;
int denum;
};
int main() {
{
const Rational r(3, 10);
if (r.Numerator() != 3 || r.Denominator() != 10) {
cout << "Rational(3, 10) != 3/10" << endl;
return 1;
}
}
{
const Rational r(8, 12);
if (r.Numerator() != 2 || r.Denominator() != 3) {
cout << "Rational(8, 12) != 2/3" << endl;
return 2;
}
}
{
const Rational r(-4, 6);
if (r.Numerator() != -2 || r.Denominator() != 3) {
cout << "Rational(-4, 6) != -2/3" << endl;
return 3;
}
}
{
const Rational r(4, -6);
if (r.Numerator() != -2 || r.Denominator() != 3) {
cout << "Rational(4, -6) != -2/3" << endl;
return 3;
}
}
{
const Rational r(0, 15);
if (r.Numerator() != 0 || r.Denominator() != 1) {
cout << "Rational(0, 15) != 0/1" << endl;
return 4;
}
}
{
const Rational defaultConstructed;
if (defaultConstructed.Numerator() != 0 || defaultConstructed.Denominator() != 1) {
cout << "Rational() != 0/1" << endl;
return 5;
}
}
cout << "OK" << endl;
return 0;
}