Create a project called daily5 and a source file called daily5.cpp. Define a cla
ID: 3599027 • Letter: C
Question
Create a project called daily5 and a source file called daily5.cpp. Define a class called Rational. The class will represent objects that are rational numbers or what we think of as fractions. Your class should have two integer member variables, one that represents the numerator of a rational number and one that represents the denominator. Write three constructors for your class: a default constructor that constructs the fraction 0/1, a single argument constructor that constructs a given integer value into a rational number by placing it as the numerator/1 and finally a two argument constructor that allows the user to select both a numerator and denominator for your rational number. The last constructor can be a bit tricky because it allows the user to give you values that are not in simplest form for example they could ask you to construct the fraction 4/2 which should be stored internally as 2/1. How can this be done? Take a look at the Euclidean algorithm for computing the greatest common divisor of two numbers (search the web). Implement this function as a helper function (private function) that your class can use when simplifying fractions. Lastly, for this assignment, overload theExplanation / Answer
this is the required code as per the question :
------------------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
public class Rational{
private :
int numerator;//stores numerator
int denominator;//stores denominator
int gcd(int n, int d);// euclid algorithm
public :
Rational();// default constructor
Rational(int n);// single parameter cnstructor
Rational(int n, int d); // two parametre constructor
int getNum(); // returns numerator
int getDeno(); // returns denominatoor
// overloaded << operator
friend ostream &operator<<( ostream& out, Rational &r )
{
out << r.getNum() <<"/"<<r.getDeno();
return out;
}
};
Ratinal :: Rational(){
numerator = 0;
denominator = 1;
}
Rational :: Rational(int n){
numerator = n;
denominator = 1;
}
Rational :: Rational(int n, int d){
int g = gcd(n,d);
numerator = n/g;
denominator = d/g;
}
int Rational :: gcd( int n, int d){
int t;
while(d != 0){
t = d;
d = n % d;
n = t;
}
return n;
}
int Rational :: getNum(){
return numerator;
}
int Rational :: getDeno(){
return denominator;
}
---------------------------------------------------------------------------------
/* hope this helps */
/* if any queries please comment */
/* thank you */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.