Answer to Question #212997 in C++ for Hemambar

Question #212997
Create a class Rational whose object can store a rational number. (For ex: 3⁄4). Include the
necessary constructors to initialize the objects and function to display the rational number in x/y
format. Define the following non-member functions.
addRational(Rational r1, Rational r2) : which should return a summation of the two input rational numbers r1 and r2.
mulRational(Rational r1, Rational r2) : which should return the product of the r1 and r2.
Set these two functions as friend to the Rational class
Main function to read two rational numbers and display the sum and product of the input by
calling the proper functions.
1
Expert's answer
2021-07-03T04:46:51-0400
#include<iostream>
using namespace std;
class Rational{
	private:
	double numerator;
		double denominator;
	public:
		Rational(int num,int den){
			numerator = num;
			denominator = den;
		}
		
		double getNumber(){
		return	numerator / denominator;
		}
friend	double addRational(Rational r1, Rational r2);
friend	double mulRational(Rational r1, Rational r2);	
		
};
double addRational(Rational r1, Rational r2){
	return r1.getNumber() + r2.getNumber();
}
double mulRational(Rational r1, Rational r2){
	return r1.getNumber()* r2.getNumber();
}
int main(){
	Rational r4(8,6);
	cout<<r4.getNumber()<<endl;
	double first_numerator, first_denominator, second_numerator,second_denominator;
	cout<<"Enter the first rational number\n";
	cout<<"Enter the numerator\t"<<endl;
	cin>>first_numerator;
	cout<<"Enter the denominator\t"<<endl;
	cin>>first_denominator;
	
	
	cout<<"Enter the second rational number\n";
	cout<<"Enter the numerator\t"<<endl;
	cin>>second_numerator;
	cout<<"Enter the denominator\t"<<endl;
	cin>>second_denominator;
	Rational r1(first_numerator,first_denominator);
	Rational r2(second_numerator,second_denominator);
	
	cout<<"The addition of the rational numbers are \t"<<addRational(r1, r2)<<endl;
	cout<<"The multiplication of the rational numbers are \t"<<mulRational(r1, r2)<<endl;
}

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