C++ MyProgrammingLab problem: Given a data type stuct Fraction{ int numerator,t
ID: 3563032 • Letter: C
Question
C++ MyProgrammingLab problem:
Given a data type
stuct Fraction{ int numerator,t denominator};
define a function
Fraction add(const Fraction & p, const Fraction & q)
that returns a Fraction object representing the sum of p and q. You may assume that neither p nor q have zero denominator.
Make sure that your result is reduced to lowest terms and doesn't have a negative denominator.
To reduce the fraction to lowest terms, you may use the function
int gcd(int a, int b)
which returns the greatest common divisor of a and b. For example, to add the fractions 3/4 and 5/6 you would use 3*6 + 4*5 = 38 as the provisional numerator and 4*6 = 24 as the provisional denominator. You would then reduce to lowest terms by dividing numerator and denominator by gcd(38,24) = 2 to obtain the final anwer 19/12.
You do not have to write the code for the gcd() function. You can just call it in the add() function.
Do not write the entire program.
Explanation / Answer
stuct Fraction{ int numerator,int denominator};
// Make sure that your result is reduced to lowest terms and doesn't have a negative denominator.
// To reduce the fraction to lowest terms, you may use the function
// which returns the greatest common divisor of a and b.
int gcd(int a, int b) {
}
// define a function
//that returns a Fraction object representing the sum of p and q. You may assume that neither p nor q have zero denominator.
Fraction add(const Fraction & p, const Fraction & q)
{
Fraction temp;
temp.numerator = p.numerator*q.denominator +q.numerator*p.denominator;
temp.denominator = q.denominator*p.denominator;
int factor = gcd(temp.numerator, temp.denominator);
temp.numerator = temp.numerator/factor;
temp.denominator = temp.denominator/factor;
return temp;
}
// For example, to add the fractions 3/4 and 5/6 you would use 3*6 + 4*5 = 38 as
// the provisional numerator and 4*6 = 24 as the provisional denominator. You would then reduce to lowest terms by dividing numerator
// and denominator by gcd(38,24) = 2 to obtain the final anwer 19/12.
// You do not have to write the code for the gcd() function. You can just call it in the add() function.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.