#include using namespace std; struct rational { int top, bot; }; void normalise(rational & r) { int a = r.top, b = r.bot; if (b < 0) { a = -a; b = -b; } while (b != 0) { int temp = a % b; a = b; b = temp; } r.top /= a; r.bot /= a; } rational fraction(int t, int b) { rational r; r.top = t; r.bot = b; normalise(r); return r; } rational number(int n) { rational r; r.top = n; r.bot = 1; return r; } const int stack_max = 1000; struct stack_of_rationals { rational data[stack_max]; int top; }; void initialise(stack_of_rationals & S) { S.top = 0; } void push(stack_of_rationals & S, rational x) { if (S.top >= stack_max) { cout << "Error! stack full\n"; return; } S.data[S.top] = x; S.top += 1; } bool isempty(stack_of_rationals & S) { return S.top == 0; } rational pop(stack_of_rationals & S) { if (S.top <= 0) { cout << "Error! stack empty\n"; return fraction(0, 1); } S.top -= 1; return S.data[S.top]; } rational read_rational() { int t, b; char c; cin >> t; c = cin.get(); if (c == '/') { cin >> b; return fraction(t, b); } else return fraction(t, 1); } void print(rational r) { if (r.bot == 1) cout << r.top; else cout << r.top << "/" << r.bot; } rational add(rational a, rational b) { return fraction(a.top*b.bot + b.top*a.bot, a.bot*b.bot); } rational sub(rational a, rational b) { return fraction(a.top*b.bot - b.top*a.bot, a.bot*b.bot); } rational mul(rational a, rational b) { return fraction(a.top*b.top, a.bot*b.bot); } rational div(rational a, rational b) { return fraction(a.top*b.bot, a.bot*b.top); } void check(rational b, rational e, string sign, rational operation(rational, rational)) { print(b); cout << " " << sign << " "; print(e); cout << " = "; print(operation(b, e)); cout << "\n"; } int main() { stack_of_rationals S; initialise(S); while (true) { char c = cin.get(); if (c=='\n' || c==' ') { } else if (c>='0' && c<='9') { cin.unget(); rational r = read_rational(); cout << " = "; print(r); cout << "\n"; push(S, r); } else { rational b = pop(S); rational a = pop(S); print(a); cout << " " << c << " "; print(b); if (c == '+') a = add(a, b); else if (c == '-') a = sub(a, b); else if (c == '*') a = mul(a, b); else if (c == '/') a = div(a, b); else cout << "Error '" << c << "' not an operator\n"; cout << " = "; print(a); cout << "\n"; push(S, a); } } }