In: Computer Science
Write a program in C++ that calculates the sum of two fractions.
The program should ask for the numerators and denominators of two
fractions and then output the sum of the two fractions. You will
need to write four functions for this program, one to read the
inputted data, one to calculate the sum of the two fractions, one
to find the Greatest Common Divider (GCD) between the numerator and
denominator and a function that will display the end result. The
program should execute in a loop, asking the use if they wish to
continue. The output should look similar as that below. Assume the
user will only enter positive numbers, and neither denominator will
ever be zero.
This program adds two fractions and displays the answer in reduced
form.
Enter numerator 1: 1
Enter denominator 1: 3
Enter numerator 2: 1
Enter denominator 2: 6
1/3 + 1/6 = 1/2
Would you like to continue? (y/n)
After using the above formula, then reduce the answer by dividing
the numerator and denominator by their GCD.
The prototypes for the four functions you will need to write are as
follows:
void readTwoFractions(int &n1, int &d1, int &n2, int
&d2);
void addTwoFractions(int n1, int d1, int n2, int d2, int &num,
int &den);
int greatestCommonDivider(int top, int bottom);
void displaySumOfFractions(int n1, int d1, int n2, int d2, int top,
int bottom);
Thanks for the question, Here is the complete program in C++
========================================================================
#include<iostream>
using namespace std;
void readTwoFractions(int &n1, int &d1, int &n2, int &d2){
cout<<"Enter numerator 1: "; cin>>n1;
cout<<"Enter denominator 1: "; cin>>d1;
cout<<"Enter numerator 2: "; cin>>n2;
cout<<"Enter denominator 2: "; cin>>d2;
}
void addTwoFractions(int n1, int d1, int n2, int d2, int &num, int &den){
num = n1*d2 + n2*d1;
den = d1*d2;
}
int greatestCommonDivider(int top, int bottom){
if(bottom==0)return top;
else
return greatestCommonDivider(bottom,top%bottom);
}
void displaySumOfFractions(int n1, int d1, int n2, int d2, int top, int bottom){
cout<<n1<<"/"<<d1<<" + "<<n2<<"/"<<d2<<" = "<<top<<"/"<<bottom<<endl;
}
int main(){
int n1, d1, n2, d2, num , den;
char calculate_again;
do{
readTwoFractions(n1,d1,n2,d2);
addTwoFractions(n1,d1,n2,d2, num,den);
int greatest_divisor = greatestCommonDivider(num,den);
num/=greatest_divisor;
den/=greatest_divisor;
displaySumOfFractions(n1,d1,n2,d2, num,den);
cout<<"\nWould you like to continue? (y/n)
";cin>>calculate_again;
}while(calculate_again!='n');
}
============================================================================