-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmixednumber.cpp
123 lines (103 loc) · 2.17 KB
/
mixednumber.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
117
118
119
120
121
122
#include "mixednumber.h"
mixedNumber::mixedNumber()
{
}
mixedNumber::~mixedNumber()
{
nukeEveryone();
}
mixedNumber::mixedNumber(int w, int n, int d)
{
setValues(w,n,d);
}
mixedNumber::mixedNumber(const double &other)
{
setValue(other);
}
mixedNumber::mixedNumber(const mixedNumber &other)
{
copy(other);
}
mixedNumber& mixedNumber::operator=(const mixedNumber &other)
{
if(this != &other)
copy(other);
return *this;
}
mixedNumber& mixedNumber::operator=(const fraction &other)
{
num = other.getNum();
denom = other.getDenom();
return *this;
}
mixedNumber& mixedNumber::operator=(const int &other)
{
fraction temp(other);
*this = temp;
return *this;
}
mixedNumber& mixedNumber::operator=(const double &other)
{
fraction temp(other);
*this = temp;
return *this;
}
void mixedNumber::getValues(int &w, int &n, int &d)
{
w = num/denom;
n = num%denom;
d = denom;
}
void mixedNumber::setValues(int w, int n, int d)
{
fraction::setValue(w*d + n, d);
}
void mixedNumber::copy(const mixedNumber &other)
{
num = other.num;
denom = other.denom;
}
void mixedNumber::nukeEveryone()
{
num = 0;
denom = 1;
}
std::ostream& operator<<( std::ostream &out, const mixedNumber &m)
{
int whole = m.num/m.denom, numerator = m.num % m.denom;
if(numerator == 0)
out<<whole;
else
if(whole == 0)
out<<numerator<<"/"<<m.denom;
else
out<<whole<<" "<<abs(numerator)<<"/"<<m.denom;
return out;
}
std::istream& operator>>( std::istream &in, mixedNumber &m)
{
std::stringstream ss;
fraction firstHalf, secondHalf;
if(in >> firstHalf) {
if(firstHalf.getDenom() == 1) {
if(in.get() != ' ') {
in.unget();
}
if(streamUtilities::hasNextFraction(in)) {
in >> secondHalf;
if(firstHalf.getNum() > 0) {
m.setValue(secondHalf.getNum(), secondHalf.getDenom());
} else {
m.setValue(secondHalf.getNum() * -1, secondHalf.getDenom());
}
m.num += firstHalf.getNum() * secondHalf.getDenom();
} else {
m.setValue(firstHalf.getNum());
}
} else {
m.setValue(firstHalf.getNum(), firstHalf.getDenom());
}
in.clear();
}
return in;
}