#include #include using namespace std; int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } struct fraction { int top, bot; fraction(int t, int b) { top = t; bot = b; normalise(); } void normalise() { if (bot == 0) { cerr << "error: zero denominator\n"; // check added after class exit(1); } if (bot < 0) // negatives added after class { bot = - bot; top = - top; } int g = gcd(top, bot); top /= g; bot /= g; } fraction multiply(const fraction g) { return fraction(top * g.top, bot * g.bot); } fraction divide(const fraction g) { return fraction(top * g.bot, bot * g.top); } fraction add(const fraction g) { return fraction(top * g.bot + bot * g.top, bot * g.bot); } fraction subtract(const fraction g) { return fraction(top * g.bot - bot * g.top, bot * g.bot); } bool lessthan(const fraction g) // added after class { return top * g.bot < bot * g.top; } void print(ostream & out = cout) // default parameter added after class { out << top << "/" << bot; } }; int main() { fraction half(1, 2); fraction quarter(1, 4); fraction seven_eighths(7, 8); fraction x = half.add(quarter); half.print(); cout << " + "; quarter.print(); cout << " = "; x.print(); // or I could have said half.add(quarter).print(); cout << "\n"; ofstream fout("test.txt"); // file part added after class if (fout.fail()) { cerr << "failed to create test.txt\n"; exit(1); } x.print(fout); fout << " < "; seven_eighths.print(fout); bool y = x.lessthan(seven_eighths); fout << " = " << (y ? "true" : "false") << "\n"; }