Solve this problem with using \"If statement\", solve both problems in one progr
ID: 3640285 • Letter: S
Question
Solve this problem with using "If statement", solve both problems in one programme.
1.Write a program that reads and stores the numerators and denomina-
tors of two fractions as integer values. For example, if the numbers 1
and 4 are entered for the first fraction, the fraction is 1/4, The program
should print the product of the two fractions as a fraction and as a dec-
imal value. For example, 1/4 * 1/2 = 1/8 or 0.125.
2.Redo Programming Project 6-but this time compute the sum of the
two fractions.
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
//PROTOTYPES
void simplify(int&, int&);
//LOCAL DECLARATIONS
int a1, b1, a2, b2;
int nu, de;
//PROCEDURES
cout << "(separate numerator and denominator with space)" << endl;
cout << "Enter first fraction: ";
cin >> a1 >> b1;
cout << "Enter second fraction: ";
cin >> a2 >> b2;
//Multiplication
cout << a1 << "/" << b1 << " * "
<< a2 << "/" << b2;
nu = a1 * a2;
de = b1 * b2;
simplify(nu, de);
cout << " = " << nu << "/" << de
<< " = " << (double) nu / de << endl;
//Addition
cout << a1 << "/" << b1 << " + "
<< a2 << "/" << b2;
nu = a1 * b2 + a2 * b1;
de = b1 * b2;
simplify(nu, de);
cout << " = " << nu << "/" << de
<< " = " << (double) nu / de << endl;
cout << endl;
cin.sync();
cin.get();
return 0;
}
//---------------------------------------------------------
// FUNCTION DEFINITIONS
//---------------------------------------------------------
/** simplify
* find greatest common divisor of numerator and denominator
* simplify numerator and denominator by dividing them by the gcd
*/
void simplify(int &numerator, int &denominator)
{
int big, small;
if (numerator == denominator)
{
numerator = 1;
denominator = 1;
return;
}
else if (numerator > denominator)
{
big = numerator;
small = denominator;
}
else
{
big = denominator;
small = numerator;
}
while (big != small)
{
int diff = big - small;
if (diff >= small)
{
big = diff;
}
else
{
big = small;
small = diff;
}
}
numerator /= small;
denominator /= small;
}
//---------------------------------------------------------
//---------------------------------------------------------