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.
#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;
}
Comments
Excellent
Leave a comment