Using C++: Create a structure Fraction which contains a numerator and a denomina
ID: 3832548 • Letter: U
Question
Using C++:
Create a structure Fraction which contains a numerator and a denominator.
a. Write a function void printFraction(Fraction f)which prints out a fraction in the following format; e.g. if the numerator is 2 and the denominator is 5, it will print out 2/5
b. Write a function Fraction mult(Fraction f1, Fraction f2) which returns a new fraction which is the product of f1 and f2.
c. Write a function Fraction add(Fraction f1, Fraction f2)which returns a new fraction which is the sum of f1 and f2. You may simply multiply each fraction by the other’s denominator to find a common denominator; e.g. (3/4)+(5/6) = (3*6/4*6)+(5*4/6*4) = 38/24. You do NOT have to reduce the fractions.
Explanation / Answer
Code:-
#include<iostream>
using namespace std;
// Declare a fraction (defines an implicit typedef)
struct Fraction
{
int num; // Declare Numerator Variable
int den; // Declare Denominator Variable
};
Fraction add(Fraction a, Fraction b);
Fraction mult(Fraction a, Fraction b);
void printFraction(Fraction a);
int main()
{
int ans;
Fraction number[2];
char c;
cout << " Enter first fraction in this form numerator/denominator ";
cin >> number[0].num >> c >> number[0].den; // 1st fraction
cout << " Enter second fraction in this form numerator/denominator ";
cin >> number[1].num >> c >> number[1].den; // 2nd fraction
printFraction(number[0]);
printFraction(number[1]);
cout << "After adding two fractions: "<<endl;
Fraction result;
result=add(number[0],number[1]);
printFraction(result);
cout << "After multiplying two fractions: "<<endl;
result=mult(number[0],number[1]);
printFraction(result);
}
Fraction add(Fraction a,Fraction b)
{
// Declare ans, the fraction resulting from the operation
Fraction ans;
// Calculate the numerator and denominator of the resulting fraction
ans.num = (a.num * b.den) + (b.num * a.den);
ans.den = a.den * b.den;
// Return the resulting fraction
return ans;
}
Fraction mult(Fraction a, Fraction b)
{
// Declare ans, the fraction resulting from the operation
Fraction ans;
// Calculate the numerator and denominator of the resulting fraction
ans.num = a.num * b.num;
ans.den = a.den * b.den;
// Return the resulting fraction
return ans;
}
void printFraction(Fraction a){
cout<<"Fraction is :- "<<a.num<<"/"<<a.den<<endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.