#include using namespace std; int gcd(int a, int b) { for (int pd = min(a, b); pd > 1; pd -= 1) if (a % pd == 0 && b % pd == 0) return pd; return 1; } struct rational { int top, bot; void simplify() { if (top == 0) { bot = 1; return; } int d = gcd(top, bot); if (d != 1) { top /= d; bot /= d; } if (bot < 0) { bot = - bot; top = - top; } } rational(int t, int b) { top = t; bot = b; simplify(); } void print() { if (top < 0) { cout << "-"; top = - top; } if (bot == 1) cout << top; else if (top > bot) { int whole = top / bot; int newtop = top - whole * bot; cout << whole << "+" << newtop << "/" << bot; } else cout << top << "/" << bot; } rational multiply(rational b) { rational r(r.top = top * b.top, r.bot = bot * b.bot); return r; } rational divide(rational b) { rational r(r.top = top * b.bot, r.bot = bot * b.top); return r; } rational add(rational b) { rational r(r.top = top * b.bot + b.top * bot, r.bot = bot * b.bot); return r; } rational subtract(rational b) { rational r(top * b.bot - b.top * bot, r.bot = bot * b.bot); return r; } }; void one_test(string s, rational a, rational b, rational c) { a.print(); cout << " " << s << " "; b.print(); cout << " is "; c.print(); cout << "\n"; } void test(rational a, rational b) { one_test("plus", a, b, a.add(b)); one_test("minus", a, b, a.subtract(b)); one_test("times", a, b, a.multiply(b)); one_test("divided by", a, b, a.divide(b)); } rational ask(string prompt) { int t, b; cout << prompt << ", top then bottom: "; cin >> t >> b; return rational(t, b); } int main() { while (true) { rational a = ask("A"); rational b = ask("B"); test(a, b); } }