Define a class for a type called Fraction. This class is used to
represent a ratio of two integers. Include mutator functions that
allow the user to set the numerator and denominator.
• Also include a member function that returns the values of the
numerator divided by the denominator as a double.
• Include an additional member function that outputs the value of
the fraction reduced to lowest terms. This will require finding the
greatest common divisor for the numerator and denominator, and
dividing by that number.
in c++
#include <iostream>
using namespace std;
//Fraction class
class Fraction
{
//private data member
int numerator;
int denominator;
public:
//default constructor
Fraction()
{
}
//parameterize constructor
Fraction(int n, int d)
{
numerator = n;
denominator = d;
}
//method to set number
void setNumber(const int n, const int d)
{
numerator = n;
denominator = d;
}
//method to get value
double getValue()
{
return numerator / (double) denominator;
}
//method to reduce fraction
void reduceFraction()
{
int d;
d = gcd(numerator, denominator);
numerator = numerator / d;
denominator = denominator / d;
cout<<endl<<endl<<"x / y =
"<<numerator<<" / "<<denominator;
}
//method to get gcd
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
};
int main()
{
//create object
Fraction f;
//method calling
f.setNumber(5, 10);
//display result
cout<<"The value is = "<<f.getValue();
//method calling
f.reduceFraction();
return 0;
}
OUTPUT:
The value is = 0.5
x / y = 1 / 2
Get Answers For Free
Most questions answered within 1 hours.