Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Fraction {
- public:
- Fraction() : Fraction(1, 1) {}
- Fraction(int num, int denom) : numerator(num), denominator(denom) {}
- Fraction(const Fraction& fract) : numerator(fract.numerator), denominator(fract.denominator) {}
- Fraction& operator+=(const Fraction& other) {
- numerator = numerator * other.denominator + denominator * other.numerator;
- denominator *= other.denominator;
- Reduction();
- return *this;
- }
- Fraction& operator-=(const Fraction& other) {
- numerator = numerator * other.denominator - denominator * other.numerator;
- denominator *= other.denominator;
- Reduction();
- return *this;
- }
- Fraction& operator*=(const Fraction& other) {
- numerator *= other.numerator;
- denominator *= other.denominator;
- Reduction();
- return *this;
- }
- Fraction& operator/=(const Fraction& other) {
- numerator *= other.denominator;
- denominator *= other.numerator;
- Reduction();
- return *this;
- }
- ~Fraction() {}
- void print() {
- std::cout << numerator << " / " << denominator << std::endl;
- }
- private:
- void Reduction() {
- int x = numerator;
- int y = denominator;
- while (x != y) {
- if (x > y) {
- x = x - y;
- }
- else {
- y = y - x;
- }
- }
- numerator /= x;
- denominator /= x;
- }
- int numerator;
- int denominator;
- };
- Fraction& operator+(const Fraction& left, const Fraction& right) {
- Fraction temp = left;
- temp += right;
- return temp;
- }
- int main() {
- Fraction a(1,2);
- Fraction b(3,4);
- a += b;
- a.print();
- a -= b;
- a.print();
- a *= b;
- a.print();
- a /= b;
- a.print();
- Fraction c = a + b;
- c.print();
- }
Advertisement
Add Comment
Please, Sign In to add comment