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

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Programm: rational.C // Brueche ganzer Zahlen. // Achtung: Programm compiliert so nicht! namespace ifm { // Klasse zur Repraesentation von Bruechen ganzer Zahlen. class Rational { public: typedef int NT; Rational(const NT& n, const NT& d); // PRE: d != 0. // POST: Bruch initialisiert als n / d. Rational(const NT& n); // POST: Bruch initialisiert als n / 1. const NT& n() const; // POST: Rueckgabewert ist Zaehler des Bruchs. const NT& d() const; // POST: Rueckgabewert ist Nenner des Bruchs. void normalize(); // POST: Zaehler und Nenner sind teilerfremd. Rational& operator+=(const Rational& x); // POST: x wurde zu *this addiert. Rational& operator-=(const Rational& x); // POST: x wurde von *this subtrahiert. private: NT n_; // numerator (Zaehler) NT d_; // denominator (Nenner) Invariante: d_ > 0. }; Rational operator+(const Rational& x, const Rational& y) // POST: Rueckgabewert ist x + y. { Rational z = x; z += y; return z; } Rational operator-(const Rational& x, const Rational& y) // POST: Rueckgabewert ist x - y. { Rational z = x; z -= y; return z; } // ... } // namespace ifm int main() { ifm::Rational q(1, 2); ifm::Rational r(2, 3); ifm::Rational x = q + r; ifm::Rational y = q - r; std::cout << "q = " << q.n() << "/" << q.d() << "\n" << "r = " << r.n() << "/" << r.d() << "\n" << "q+r = " << x.n() << "/" << x.d() << "\n" << "q-r = " << y.n() << "/" << y.d() << std::endl; return 0; }