Answer to Question #281465 in C++ for jye

Question #281465

Construct a class of fractions with both numerator and denominator being floats. Define the following functions in the class:


constructor

Operator functions for addition, subtraction, multiplication, and division of two fractions

Function input operator, output operator a fraction

Write a main program using the above fraction.


1
Expert's answer
2021-12-20T14:49:27-0500
#include <iostream>


class Fraction
{
    float denominator;
    float numerator;
public:


    Fraction()
    {
        numerator = 1;
        denominator = 1;
    }
    Fraction(int n, int d)
    {
        numerator = n;
        if (d == 0)
        {
            std::cout << "ERROR: ATTEMPTING TO DIVIDE BY ZERO" << std::endl;
            exit(0); 
        }
        else
            denominator = d;
    }
 
    Fraction Sum(Fraction otherFraction)
    {
        int n = numerator * otherFraction.denominator + otherFraction.numerator * denominator;
        int d = denominator * otherFraction.denominator;
        return Fraction(n / gcd(n, d), d / gcd(n, d));
    }
    Fraction Difference(Fraction otherFraction)
    {
        int n = numerator * otherFraction.denominator - otherFraction.numerator * denominator;
        int d = denominator * otherFraction.denominator;
        return Fraction(n / gcd(n, d), d / gcd(n, d));
    }
    Fraction Product(Fraction otherFraction)
    {
        int n = numerator * otherFraction.numerator;
        int d = denominator * otherFraction.denominator;
        return Fraction(n / gcd(n, d), d / gcd(n, d));
    }
    Fraction Division(Fraction otherFraction)
    {
        int n = numerator * otherFraction.denominator;
        int d = denominator * otherFraction.numerator;
        return Fraction(n / gcd(n, d), d / gcd(n, d));
    }
  
    int gcd(int n, int d)
    {
        int remainder;
        while (d != 0)
        {
            remainder = n % d;
            n = d;
            d = remainder;
        }
        return n;
    }
    void show() 
    {
        if (denominator == 1)
            std::cout << numerator << std::endl;
        else
            std::cout << numerator << "/" << denominator << std::endl;
    }
};


int main()
{
    Fraction a(1, 2);
    Fraction b(1, 4);
    Fraction c;


    c = a.Sum(b); 
    c.show();


    c = a.Difference(b); 
    c.show();


    c = a.Product(b); 
    c.show();


    c = a.Division(b); 
    c.show();


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog