#include using namespace std; struct fraction { int top, bot; }; int gcd(int a, int b) // There is a much better (faster) method than this. It is called // Euclid's Algorithm. You might want to look it up. We stuck with // this slow version because it doesn't require any knowledge that // you can't be expected to have yet. { for (int i = max(a, b); i >= 1; i -= 1) if (a % i == 0 && b % i == 0) return i; return 1; } void correct(fraction & f) { int d = gcd(f.top, f.bot); f.top /= d; f.bot /= d; } void set(fraction & f, int t, int b) { f.top = t; f.bot = b; correct(f); } void print(fraction f) { cout << f.top << "/" << f.bot; } fraction add(fraction x, fraction y) { fraction R; set(R, x.top * y.bot + y.top * x.bot, x.bot * y.bot); correct(R); return R; } fraction subtract(fraction x, fraction y) { fraction R; set(R, x.top * y.bot - y.top * x.bot, x.bot * y.bot); correct(R); return R; } fraction multiply(fraction x, fraction y) { fraction R; set(R, x.top * y.top, x.bot * y.bot); correct(R); return R; } fraction divide(fraction x, fraction y) { fraction R; set(R, x.top * y.bot, x.bot * y.top); correct(R); return R; } bool less(fraction x, fraction y) // just an example, there would be a number of different comparing functions. { return x.top * y.bot < y.top * x.bot; } int main() { fraction A, B; set(A, 1, 2); // A = 1/2; set(B, 3, 4); // B = 3/4 fraction C = add(A, B); print(C); cout << "\n"; }