Write a C++ program that conducts the rational number operations. Your program w
ID: 3660755 • Letter: W
Question
Write a C++ program that conducts the rational number operations. Your program will use a rational number class to perform theaddition, subtraction, multiplication, and divisionoperationson two fractions. You are required to write this class as part of this assignment. For now, assume that the user will enter the numerator and the denominator of the first fraction, followed by those for the second fraction.
You need to use constructors for:
1) correctly initializing variable members, and
2) creating objects with given initial values. Note that a fraction may have both a numerator and a denominator, for example: (8/3), or may simply be a number, for example: 6, in which case you will actually use (6/1) to represent it. Thus, the constructors with two and one arguments should be included in the class definition.
Your class will have a function for each one of the four operations. For example: Suppose we have defined objects a and b as two fractions, then to compute a + b, we will use:
a.add(b);
When you conduct an operation, you do not have to simplify the result, i.e., 4/5 * 5/10 = 20/50.
Here are some of the rules you may need:
a/b + c/d = (a*d + b*c) / (b*d)
a/b - c/d = (a*d - b*c) / (b*d)
(a/b) * (c/d) = (a*c) / (b*d)
(a/b) / (c/d) = (a*d) * (c*b)
Explanation / Answer
#include using namespace std; class Rational{ int num, denom; public: //constructors Rational();//default constructor Rational(int, int);//sets denom to 1 if invalid input Rational(int wholeNumber); void input(int,int);//input data member values int getNum(); int getDenom(); void showData(); //display data member values Rational operator+(const Rational &); Rational operator-(const Rational &); Rational operator*(const Rational &); Rational operator/(const Rational &); Rational add(const Rational &); Rational subtract(const Rational &); Rational multiply(const Rational &); Rational divide(const Rational &); }; Rational::Rational(){//default constructor num=0; denom=1; } Rational::Rational(int n, int d){//sets denom to 1 if invalid input input(n,d); } Rational::Rational(int n){//single num=n; denom=1; } void Rational::input(int n,int d){ num=n; if(d>0) //if + denom=d; else if(dRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.