-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmixednumber.cpp
More file actions
139 lines (122 loc) · 2.64 KB
/
mixednumber.cpp
File metadata and controls
139 lines (122 loc) · 2.64 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include "mixednumber.h"
mixedNumber::mixedNumber()
{
}
mixedNumber::mixedNumber(long long int w, long long int n, long long int d)
{
setFraction(d*w+n,d);
}
mixedNumber::mixedNumber(const fraction &other)
{
copy(other);
}
mixedNumber::~mixedNumber()
{
}
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)
{
copy(other);
return *this;
}
void mixedNumber::copy(const mixedNumber &other)
{
setFraction(other.getNum(), other.getDenom());
}
void mixedNumber::copy(const fraction &other)
{
setFraction(other.getNum(), other.getDenom());
}
void mixedNumber::setValue(long long int w, long long int n, long long int d)
{
setFraction(d*w+n, d);
}
ostream& operator<<(ostream& out, const mixedNumber &x)
{
long long int whole = x.getNum()/x.getDenom(), num;
if(whole != 0)
num = abs(x.getNum()) % x.getDenom();
else
num = x.getNum();
{
if(num != 0)
{
if(whole != 0)
out<<whole<<" ";
out<<num<<"/"<<x.getDenom();
}
else
{
out<<whole;
}
}
return out;
}
istream& operator>>(istream& in, mixedNumber &x)
{
long long int whole = 0, num = 0, denom = 1;
char junk;
if(in.peek() == '.')
{
whole = 0;
in>>junk>>num;
denom = 10;
while((num/denom) >= 1)
denom *= 10;
}
else
{
in>>whole;
if(in.peek() == '/')
{
in>>junk;
if(isdigit(in.peek()))
{
num = whole;
whole = 0;
in>>denom;
}
else
{
num = 0;
denom = 1;
in.unget();
}
}
else if(in.peek() == '.')
{
in>>junk>>num;
denom = 10;
while((num/denom) >= 1)
denom *= 10;
}
else
{
char space = in.get();
if(space != ' ')
in.unget();
else
if(in.peek() >='0' && in.peek() <= '9')
{
in >>num>>junk>>denom;
}
else
in.unget();
}
}
cout<<"whole = "<<whole<<" num = "<<num<<" denom = "<<denom<<endl;
if(whole < 0)
x.setFraction(-(denom*abs(whole)+num), denom);
else
x.setFraction(denom*whole+num, denom);
return in;
}