Answer to Question #345374 in C++ for Umi

Question #345374

b. Use the fraction structure from Part a, implement four-function fraction calculator. It uses


functions for each of the four arithmetic operations. They can be called fadd(), fsub(), fmul(), and


fdiv(). Each of these functions should take two arguments of type struct fraction, and return an


argument of the same type.

1
Expert's answer
2022-05-26T16:56:24-0400
#include <iostream>
using namespace std;


struct fraction{
    int numerator;
    int denominator;
    
    fraction operator+(fraction b){
        return fraction{numerator+b.numerator, denominator+b.denominator};
    }
    
};
fraction fadd(fraction a, fraction b){
    return fraction{a.numerator+b.numerator, a.denominator+b.denominator};
}
fraction fsub(fraction a, fraction b){
    return fraction{a.numerator-b.numerator, a.denominator-b.denominator};
}
fraction fmul(fraction a, fraction b){
    return fraction{a.numerator*b.numerator, a.denominator*b.denominator};
}
fraction fdiv(fraction a, fraction b){
    return fraction{a.numerator/b.numerator, a.denominator/b.denominator};
}


ostream& operator<<(ostream& os, const fraction& fr)
{
    os << "["<<fr.numerator << ',' << fr.denominator << ']';
    return os;
}


int main()
{
    fraction f1, f2, result;
    
    cout<<"Enter numerator1: ";
    cin>>f1.numerator;
    cout<<"Enter denominator1: ";
    cin>>f1.denominator;




    cout<<"Enter numerator2: ";
    cin>>f2.numerator;
    cout<<"Enter denominator2: ";
    cin>>f2.denominator;
        
    result = fdiv(f1,f2);
    cout<< result;
    
    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

Umi
27.05.22, 09:14

Excellent

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS