In: Computer Science
//C++ Code
#include<iostream>
using namespace std;
class Rational {
private:
int num, den;
void simplify()
{
//reduced to simplest form
for (int i = this->den *
this->num; i > 1; i--) {
if
((this->den % i == 0) && (this->num % i == 0))
{
this->den /= i;
this->num /= i;
}
}
}
public:
//defaulat constructor
Rational();
//overlaod constructor
Rational(int n, int d);
//member functions
Rational& add(const Rational other);
Rational& mul(const Rational other);
Rational& div(const Rational other);
Rational& sub(const Rational other);
bool less(const Rational other);
bool eq(const Rational other);
bool neq(const Rational other);
//overload ostream
friend ostream& operator<<(ostream& out,
const Rational& other);
};
//implementation
//defaulat constructor
Rational::Rational()
{
num = 0;
den = 1;
}
//overlaod constructor
Rational::Rational(int n, int d)
{
if (d < 0)
{
d = d * -1;
n = n * -1;
}
num = n;
den = d;
simplify();
}
//member functions
Rational& Rational::add(const Rational other)
{
Rational temp;
temp.num = num * other.den + other.num * den;
temp.den = den * other.den;
temp.simplify(); //calling the helper function to
reduce the fraction
return temp;
}
Rational& Rational::mul(const Rational other)
{
Rational temp; //creating a temporary object
temp.num = num * other.num;
temp.den = den * other.den;
temp.simplify(); //calling the helper function to
reduce the fraction
return temp;
}
Rational& Rational::div(const Rational other)
{
Rational temp; //creating a temporary object
temp.num = num * other.den;
temp.den = den * other.num;
temp.simplify(); //calling the helper function to
reduce the fraction
return temp;
}
Rational& Rational::sub(const Rational other)
{
Rational temp;
temp.num = num * other.den - other.num * den;
temp.den = den * other.den;
temp.simplify(); //calling the helper function to
reduce the fraction
return temp;
}
bool Rational::less(const Rational other)
{
return num * other.den < other.num * den;
}
bool Rational::eq(const Rational other)
{
return num * other.den == other.num * den;
}
bool Rational::neq(const Rational other)
{
return num * other.den != other.num * den;
}
//overload ostream
ostream& operator<<(ostream& out, const Rational&
other)
{
out << other.num << "/" <<
other.den;
return out;
}
//main()
int main()
{
//Create objects
Rational r1(3, 4), r2(7, 5);
Rational addR = r1.add(r2);
cout << r1 << " + " << r2 << "
= " << addR << endl;
Rational subR = r1.sub(r2);
cout << r1 << " - " << r2 << "
= " << subR << endl;
Rational mulR = r1.mul(r2);
cout << r1 << " * " << r2 << "
= " << mulR << endl;
Rational divR = r1.div(r2);
cout << r1 << " / " << r2 << "
= " << divR << endl;
cout << r1 << " == " << r2
<< (r1.eq(r2)?" true":" false") << endl;
cout << r1 << " < " << r2
<< (r1.less(r2) ? " true" : " false") << endl;
cout << r1 << " != " << r2 <<
(r1.neq(r2) ? " true" : " false") << endl;
return 0;
}
//Output
//If you need any help regarding this solution...... please leave a comment...... thanks