/* 1 */ #include /* 2 */ /* 3 */ /* 4 */ /* 5 */ /* 6 */ using namespace std; /* 7 */ /* 8 */ /* 9 */ class fraction /* 10 */ { /* 11 */ private: /* 12 */ int num; // numerator /* 13 */ int denom; // denominator >0 /* 14 */ /* 15 */ void fixdenom() /* 16 */ { /* 17 */ if (denom == 0) /* 18 */ { /* 19 */ cout << "denominator cannot be 0; 1 assigned instead." /* 20 */ << endl; /* 21 */ denom = 1; /* 22 */ return; /* 23 */ } /* 24 */ if (denom < 0) // put all negative signs in numerator /* 25 */ { /* 26 */ num *= -1; /* 27 */ denom = denom * -1; /* 28 */ return; /* 29 */ } /* 30 */ } /* 31 */ /* 32 */ public: /* 33 */ /* 34 */ fraction() /* 35 */ { /* 36 */ num = 0; /* 37 */ denom = 1; /* 38 */ } /* 39 */ /* 40 */ /* 41 */ fraction(int n, int d) /* 42 */ { /* 43 */ num = n; /* 44 */ denom = d; /* 45 */ } /* 46 */ /* 47 */ fraction(int n) /* 48 */ { /* 49 */ num = n; /* 50 */ denom = 1; /* 51 */ } /* 52 */ /* 53 */ /* 54 */ void read() /* 55 */ { /* 56 */ cout << "Enter a fraction (omit the '/'): "; /* 57 */ cin >> num >> denom; /* 58 */ fixdenom(); /* 59 */ } /* 60 */ /* 61 */ void write() const /* 62 */ { /* 63 */ cout << num << "/" << denom; /* 64 */ } /* 65 */ /* 66 */ //bool greaterthan(const fraction& a) /* 67 */ bool operator<(const fraction& a) /* 68 */ { /* 69 */ return ((num * a.denom) < (a.num * denom)); /* 70 */ } /* 71 */ /* 72 */ /* 73 */ bool operator==(const fraction& a) /* 74 */ { /* 75 */ // see if 2 nums and 2 denoms are equal /* 76 */ // return true or false /* 77 */ return ((num * a.denom) == (a.num * denom)); /* 78 */ } /* 79 */ /* 80 */ void add(const fraction& a, const fraction& b) /* 81 */ { /* 82 */ num = (a.num*b.denom) + (b.num*a.denom); /* 83 */ denom = a.denom * b.denom; /* 84 */ reduce(); /* 85 */ } /* 86 */ /* 87 */ void multiply(const fraction& a, /* 88 */ const fraction& b) /* 89 */ { /* 90 */ num = a.num*b.num; /* 91 */ denom = a.denom*b.denom; /* 92 */ reduce(); /* 93 */ } /* 94 */ /* 95 */ // must be before reduce, or must have a prototype /* 96 */ int findgcd(int a, int b) /* 97 */ { /* 98 */ // get absolute value of both num and denom /* 99 */ if (a < 0) /*100 */ a*= -1; /*101 */ if (b < 0) /*102 */ b *= -1; /*103 */ /*104 */ // get lowest number /*105 */ int lowest = a; /*106 */ if (b < lowest) /*107 */ lowest = b; /*108 */ /*109 */ // from lowest downto 1, find largest nbr divisible by both a and b /*110 */ for (int i=lowest;i>=1;i--) /*111 */ if ((a % i == 0) && (b % i == 0)) /*112 */ return i; /*113 */ } /*114 */ /*115 */ /*116 */ void reduce() /*117 */ { /*118 */ int gcd = findgcd(num, denom); /*119 */ num /= gcd; /*120 */ denom /= gcd; /*121 */ } /*122 */ /*123 */ int getnum() const /*124 */ { /*125 */ return num; /*126 */ } /*127 */ /*128 */ int getdenom() const /*129 */ { /*130 */ return denom; /*131 */ } /*132 */ /*133 */ void setdenom(int d) /*134 */ { /*135 */ denom = d; /*136 */ fixdenom(); /*137 */ } /*138 */ /*139 */ void setnum(int n) /*140 */ { /*141 */ num = n; /*142 */ } /*143 */ /*144 */};