a. Include a member function named gcd() in the Fractions class constructed for
ID: 3686460 • Letter: A
Question
a. Include a member function named gcd() in the Fractions class constructed for
Exercise 5a that reduces a fraction to its lowest common terms, such as reducing the fraction
2/4 to 1/2. This is done by dividing both the numerator and denominator values by their greatest
common divisor. (See Exercise 10 in “Programming Projects for Chapter 6” for a description
of finding the greatest common divisor of two numbers.)
b. Modify the overloaded operator constructor written for Exercise 5a to include a call to
gcd() so that each overloaded operator function uses gcd() to return a fraction in lowest
common terms.
Explanation / Answer
/*Headers*/
#include "stdafx.h"
#include <iostream>
using namespace std;
/*INTILIZATION*/
class Fraction
{
/*Constructor*/
public:
/*Disp*/
void output1()
{
double decimal = static_cast<double> (numerator) / denominator;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(4);
cout << "fraction as a decimal is : " << decimal << ". ";
}
void output2()
{
int temp, gcd;
/*loop*/
while (denominator != 0)
{
temp = denominator;
denominator = numerator % denominator;
numerator = temp;
gcd = numerator;
}
cout << "Lowest term of the fraction is : " << (numerator / gcd) << "/" << (denominator / gcd) << ". ";
}
void input()
{
cout << "Enter a integer for the numerator: ";
cin >> numerator;
cout << "Enter a integer for the denominator: ";
cin >> denominator;
}
private:
/*Integer decleration*/
int numerator;
int denominator;
};
/*Main method*/
int main()
{
/*
Fraction number1;
number1.input();
number1.output1();
number1.output2();
/*To stand the output in the display the screen*/
system("pause")
return();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.