Answer to Question #327098 in C++ for gdsg

Question #327098

Define a class RationalNumber with suitable data members and member function.

Overload the different operators participating in the following expression to get the result


1
Expert's answer
2022-04-13T02:14:53-0400
class RationalNumber
{
private:
	int numerator;
	int denominator;
public:
	RationalNumber(int num, int denom) : numerator(num), denominator(denom) {}

	RationalNumber(int num) : numerator(num), denominator(1) {}

	RationalNumber operator+(const RationalNumber& second_number)
	{
		if (this->denominator == second_number.denominator)
		{
			return RationalNumber(this->numerator + second_number.numerator, denominator);
		}
		else
		{
			return RationalNumber(this->numerator * second_number.denominator + second_number.numerator * this->denominator, this->denominator * second_number.denominator);
		}
	}

	RationalNumber operator-(const RationalNumber& second_number)
	{
		if (this->denominator == second_number.denominator)
		{
			return RationalNumber(this->numerator - second_number.numerator, denominator);
		}
		else
		{
			return RationalNumber(this->numerator * second_number.denominator - second_number.numerator * this->denominator, this->denominator * second_number.denominator);
		}
	}

	RationalNumber operator*(const RationalNumber& second_number)
	{
		return RationalNumber(this->numerator * second_number.numerator, this->denominator * second_number.denominator);
	}

	RationalNumber operator/(const RationalNumber& second_number)
	{
		return RationalNumber(this->numerator * second_number.denominator, this->denominator * second_number.numerator);
	}

	int get_numerator()
	{
		return numerator;
	}

	int get_denominator()
	{
		return denominator;
	}

	void set_numerator(int num)
	{
		numerator = num;
	}

	void set_denominator(int denom)
	{
		denominator = denom;
	}
};

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS