-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRational.cpp
102 lines (79 loc) · 1.84 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
// Thien Trinh
// CSE 374
// Homework 7
// 06/06/2019
/*
Implementation of Rational.h
If no number is entered, constructs a Rational object with 0/1
If only one number is entered, constructs a Rational object with n/1
If two number is entered, constructs a Rational object with n/d
*/
# include "Rational.h"
# include <cstdlib>
# include <stdio.h>
namespace rational374 {
static int gcd(int n, int d);
// Constructors
Rational::Rational() {
numer_ = 0;
denom_ = 1;
}
Rational::Rational(int n) {
numer_ = n;
denom_ = 1;
}
Rational::Rational(int n, int d) {
numer_ = n;
denom_ = d;
int div_ = gcd(numer_, denom_);
numer_ = numer_ / div_;
denom_ = denom_ / div_;
}
// Accessors
int Rational::n() const {
return numer_;
}
int Rational::d() const {
return denom_;
}
// Arithmetic
Rational Rational::plus(Rational other) const {
int n1 = n();
int d1 = d();
int n2 = other.n();
int d2 = other.d();
return Rational(((n1 * d2) + (n2 * d1)), d1 * d2);
}
Rational Rational::minus(Rational other) const {
int n1 = n();
int d1 = d();
int n2 = other.n();
int d2 = other.d();
return Rational(((n1 * d2) - (n2 * d1)), d1 * d2);
}
Rational Rational::times(Rational other) const {
int n1 = n();
int d1 = d();
int n2 = other.n();
int d2 = other.d();
return Rational(n1 * n2, d1 * d2);
}
Rational Rational::div(Rational other) const {
int n1 = n();
int d1 = d();
int n2 = other.n();
int d2 = other.d();
return Rational(n1 * d2, d1 * n2);
}
// Helper method that finds the greatest common divisor of
// two numbers in the arguments and returns it.
static int gcd(int n, int d) {
n = abs(n);
d = abs(d);
if (d == 0) {
return n;
} else {
return gcd(d, n % d);
}
}
}