#include #include int main(){ std::cout << "enter two rational numbers in the form n:d each " << std::endl; // enter two numbers // output if the two equals // output the sum of the two } /* story: 1.) add type rational and functionality such as input, add, equals and output struct rational{ int n; int d; } rational add(rational l, rational r){ rational result; result.n = l.n* r.d + r.n * l.d; result.d = l.d * r.d; return result; } void input(std::istream& in, rational& r){ char ignore; in >> r.n >> ignore >> r.d; assert(ignore=':'); assert(r.d != 0); } void output(std::istream& out, const rational& r){ out << r.n << ":" << r.d; } bool equals(rational l, rational r){ return l.n*r.d == r.n*l.d; } 2.) non-idiomatic add --> idiomatic add rational add(rational l, const rational& r){ l = l.n* r.d + r.n * l.d; l.d *= r.d; return l; } 3.) Operator overloading -- basic replace add --> operator+ show functional form then infix form replace out --> operator<< show operator<<(operator<<(std::cout, l),r); and then infix. replace in --> operator>> replace equals --> operator== 4.) Operator overloading: arithmetic assignments rational& operator+=(rational& l, const rational& r){ l.n = l.n* r.d + r.n * l.d; l.d *= r.d; return l; } then simplify addition from before rational add(rational l, const rational& r){ l += r; return l; } 5.) unary operators - ++x and x++ rational operator-(rational l){ l.n = -l.n; return l; } rational& operator++(rational& l){ l.n += l.d; return l; } rational operator++(rational& l, int){ // to discriminate ++x from x++ rational r = l; l.n += l.d; return r; } 6.) if time allows: add gcd and normalize // pre: a, b >= 0 // post: return greatest common divisor of a and b int gcd(int a, int b){ if (b != 0){ return gcd(b, a % b); } return a; } rational& reduce(rational& l){ // kürzen, normalisieren if (l.d < 0) { l.n = -l.n; l.d = -l.d; } bool negative = l.n<0; if (negative) l.n = -l.n; int k = gcd(l.n,l.d); l.n /= k; l.d /= k; if (negative) l.n = -l.n; return l; } then apply to operator+= (etc.) rational& operator+=(rational& l, const rational& r){ l.n = l.n* r.d + r.n * l.d; l.d *= r.d; return reduce(l); }