1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #ifndef _RATIONAL_H #define _RATIONAL_H #include <iostream> using std::ostream; using std::istream; using std::cout; using std::cin; using std::endl; class Rational { private: int Down; int Up; public: Rational(); Rational(int); Rational(int, int); Rational(const Rational&); void Print() const; void Optimise(); friend Rational operator +(Rational, Rational); friend Rational operator -(Rational, Rational); friend Rational operator *(Rational, Rational); friend Rational operator /(Rational, Rational); friend bool operator ==(Rational, Rational); friend ostream & operator <<(ostream &, const Rational &); friend istream & operator >>(istream &, Rational &); operator double(); }; #endif Rational::Rational() { Down = 1; Up = 0; } Rational::Rational(int u) { Down = 1; Up = u; } Rational::Rational(int u, int d) { Down = d; Up = u; Optimise(); } Rational::Rational(const Rational &r) { Down = r.Down; Up = r.Up; Optimise(); } void Rational::Print() const{ cout << Up << '/' << Down; } void Rational::Optimise() { if (Down == 0) { cout << "错误,分母不能为0" << endl; cout << "请重新输入分子和分母:"; cin >> *this; } if (Up == 0) { Down = 1; return; } int p = Down, q = Up, t; bool a = 0; if (p*q < 0) { a = 1; p = p > 0 ? p : (-p); q = q > 0 ? q : (-q); } if (p < q) { t = q; q = p; p = t; } while (t = p % q, t != 0) { p = q; q = t; } Down /= q; Up /= q; Down = Down > 0 ? Down : (-Down); Up = Up > 0 ? Up : (-Up); if (a) Up = -Up; return; } Rational operator +(Rational t, Rational r) { return Rational(t.Up*r.Down+t.Down*r.Up, t.Down*r.Down); } Rational operator -(Rational t, Rational r) { return Rational(t.Up*r.Down-t.Down*r.Up, t.Down*r.Down); } Rational operator *(Rational t, Rational r) { return Rational(t.Up*r.Up, t.Down*r.Down); } Rational operator /(Rational t, Rational r) { return Rational(t.Up*r.Down, t.Down*r.Up); } bool operator ==(Rational r1, Rational r2) { if (r1.Down == r2.Down&&r1.Up == r2.Up) return true; else return false; } istream & operator>>(istream &in, Rational &r) { int d, u; in >> u >> d; r.Down = d; r.Up = u; r.Optimise(); return in; } ostream & operator<<(ostream &out, const Rational &r) { out << r.Up << '/' << r.Down; return out; } Rational::operator double() { return double(Up) / double(Down); }
|