-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathclasses.cpp
79 lines (61 loc) · 1.95 KB
/
classes.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
#include <iomanip>
#include <iostream>
#include <sstream>
#include <numeric>
class Fraction {
public:
// ADD YOUR CODE HERE
std::string str() const {
std::ostringstream oss;
oss << m_num << '/' << m_denom;
return oss.str();
}
int numerator() const {
return m_num;
}
int denominator() const {
return m_denom;
}
private:
void normalize() {
const int gcd = std::gcd(m_num, m_denom);
m_num /= gcd;
m_denom /= gcd;
}
int m_num, m_denom;
};
// ADD YOUR CODE HERE
// This is using the cpp, the C preprocessor to expand a bit of code
// (the what argument) to a pair containing a string representation
// of it and the code itself. That way, print is given a string and a
// value where the string is the code that lead to the value
#define CHECK(print,what) print(#what, what)
unsigned int WIDTH {20};
void printTestResult(std::string const & what, bool passed) {
std::cout << std::setw(WIDTH) << what << ": " << (passed ? "PASS" : "** FAIL **") << '\n';
}
int main() {
// create a fraction with values 3 (which is 3/1) and 1/3
std::cout<<std::endl;
const Fraction three{3};
const Fraction third{1, 3};
std::cout<<three.str()<<' '<<third.str()<<'\n';
// equality
std::cout<<std::endl;
CHECK(printTestResult,equal(three,three));
CHECK(printTestResult,equal(third,third));
CHECK(printTestResult,equal(three,Fraction{3}));
CHECK(printTestResult,equal(three,Fraction{3, 1}));
CHECK(printTestResult,equal(third,Fraction{1, 3}));
CHECK(printTestResult,equal(Fraction{3},three));
CHECK(printTestResult,equal(Fraction{1, 3},third));
CHECK(printTestResult,equal(third,Fraction{2, 6}));
// multiply
std::cout<<std::endl;
CHECK(printTestResult,equal(multiply(third,2),Fraction{2, 3}));
CHECK(printTestResult,equal(multiply(2,third),Fraction{2, 3}));
CHECK(printTestResult,equal(multiply(three,third),Fraction{1, 1}));
CHECK(printTestResult,equal(multiply(3,third),1));
// end
std::cout<<std::endl;
}