Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Program: userational.cpp // Add two rational numbers. #include // the new type rational struct rational { int n; int d; // INV: d != 0 }; // POST: return value is the sum of a and b rational add (const rational a, const rational b) { rational result; result.n = a.n * b.d + a.d * b.n; result.d = a.d * b.d; return result; } int main () { // input std::cout << "Rational number r:\n"; rational r; std::cout << " numerator =? "; std::cin >> r.n; std::cout << " denominator =? "; std::cin >> r.d; std::cout << "Rational number s:\n"; rational s; std::cout << " numerator =? "; std::cin >> s.n; std::cout << " denominator =? "; std::cin >> s.d; // computation const rational t = add (r, s); // output std::cout << "Sum is " << t.n << "/" << t.d << ".\n"; return 0; }