#include #include struct rational{ int n; int d; // INV d != 0; }; // 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; } // post: normalize (r.d > 0) and reduce r rational& reduce(rational &r){ if (r.d < 0) { r.n = -r.n; r.d = -r.d; } bool negative = r.n<0; if (negative) r.n = -r.n; int k = gcd(r.n,r.d); r.n /= k; r.d /= k; if (negative) r.n = -r.n; return r; } rational& operator+=(rational& l, const rational& r){ l.n = l.n*r.d + l.d * r.n; l.d *= r.d; return reduce(l); } rational operator+(rational l, const rational& r){ return l += r; } bool operator==(const rational& a, const rational&b){ return a.d * b.n == b.d * a.n; } std::istream& operator>>(std::istream& in, rational& l){ char ignore; in >> l.n >> ignore >> l.d; assert(ignore == ':'); assert(l.d != 0); return in; } std::ostream& operator<<(std::ostream& out, const rational& r){ return out << r.n << ":" << r.d; } int main () { std::cout << "enter two rational numbers in the form n:d each " << std::endl; rational r; rational s; std::cin >> r >> s; if (r == s) { std::cout << "interesting: two equal numbers..." << std::endl; } std::cout << r << " + " << s << " = " << r+s << std::endl; } /* story: 1.) make struct a class will not compile any more add constructors: two elements, int (conversion) default add operator+= add out / in member functions std::ostream& output(std::ostream& out) { // forget const return out << n << ":" << d; } std::istream& input(std::istream& in){ char ignore; in >> n >> ignore >> d; assert(ignore == ':'); assert(l.d != 0); return in; } std::istream& operator>>(std::istream& in, rational& l){ return l.input(in); } std::ostream& operator<<(std::ostream& out, const rational& r){ return r.output(out); } add operators "==" and "+=" in the scope of rational for "+=" add reduce to the private functions! bool operator==(const rational& r){ // forgot const return n * r.d == d + r.n; } try program with a const rational --> const in out and in "==" add numerator / denominator functions show rational s = r + 1; // auto conversion to int show // conversion to double operator double(){ return 1.0*n/d; } */