Question

In: Computer Science

Write a rational number class in C++. Recall a rational number is a rational number, composed...

Write a rational number class in C++. Recall a rational number is a rational number, composed of two integers with division indicated. The division is not carried out, it is only indicated, as in 1/2, 2/3, 15/32. You should represent rational numbers using two int values, numerator and denominator.

A principle of abstract data type construction is that constructors must be present to create objects with any legal values. You should provide the following two constructors:

  1. one constructor to make rational objects without any argument. The constructor sets the rational object's numerator to 0, and denominator to 1.
  2. one constructor to make rational objects out of pairs of int values, i.e., a constructor with two int parameters. The constructor uses the two values to initialize the rational object's numerator and denominator respectively.
  3. one constructor to make rational objects out of a single int values, as in 2/1, 17/1, i.e., a constructor with only one int parameter. The constructor sets the rational’ s numerator to the given parameter and sets the denominator to 1.

Remember the rules for a rational number. You constructor (and every mutator function) must enforce the rules!

EXTRA CREDIT: Feel free to write one constructor with default values.

You should also provide the following member functions:

  1. an input function that reads from standard input the value for current object. The input should be in the form of 2/3 or 27/51. [Enforce simple rules for rational numbers.]
  2. an output function that displays the current object in the terminal. The output should also be in the form of 2/3, i.e., numerator/denominator.
  3. Two getter functions that return the numerator and denominator respectively.
  4. a Sum function that takes two rational objects as parameters. It sets the current rational object to be the sum of the two given rational numbers.

Note the following formula for adding two rational numbers:

a/b + c/d = ( a*d + b*c)/(b*d)

Starter code:

int main()
{
  // ToDo: declare three rational objects using the default constructor
char answer;


// Main loop to read in rationals and compute the sum
do {
cout << "\nEnter op1 (in the format of p/q):";
  // ToDo: use your input member function to read the first rational


cout << "\nEnter op2 (in the format of p/q):";
  // ToDo: use your input member function to read the second rational


  // ToDo: use the third rational to call Sum with first and second as parameters


cout << "\nThe sum of op1 and op2 is:";
  // ToDo: ouptput the third rational


cout << endl;
cout << "\nTry again (Y/N)?";
cin >> answer;
} while (answer == 'y' || answer == 'Y');

  // ToDo: test getters on rational that has the sum above.
cout << "\nC's numerator is: " ;
cout << "\nC's denominator is: ";

    // TODO: Use two constructors to declare a whole number 3/1 and a 4/5

    // TODO: Use output to print both rationals

return 0;
}

Sample output:

Enter op1 (in the format of p/q): 3/4
Enter op2 (in the format of p/q): 4/5
The sum of op1 and op2 is: 31/20

Try again (Y/N)? 
Enter op1 (in the format of p/q): 9/0
wrong input.
Enter a rational (p/q):9/3
Enter op2 (in the format of p/q): 4/31
The sum of op1 and op2 is: 291/93 
Try again (Y/N)? 

C's numerator is: 291 
C's denominator is: 93 
3/1 4/5

Solutions

Expert Solution

The above diagram shows how your code should be formatted

CODE:

=====================================

#include <iostream>
#include <cstdlib>
#include <string>
#include <cmath>
#include <sys/time.h>

using namespace std;

class Addition_Rational
{
private:   
   int numerator;
   int denominator;

public:
//default constructor (no argument)
Addition_Rational();

//parameterized constructor - only takes numerator
Addition_Rational(int i);

//parameterized constructor - takes both numerator and denominator
Addition_Rational(int p, int q);

//function to read the number in p/q format
void input();

//function to write the number in p/q format
void result();

//function to get numerator
int get_Numerator();

//function to get the denominator
int get_Denominator();

//function to produce the sum of the two rational numbers. Formula for addition: a/b + c/d = (a*d + b*c)/(b*d)
void sum(Addition_Rational a, Addition_Rational b);

// test if two rational numbers are equal.
//bool isEqual(const Addition_Rational& op);

};

int main()
{
//declare three rational objects using the default constructor
Addition_Rational p_q1, p_q2, pq;
char answer;

//main loop to read the rationals numbers and compute the sum
do {
       //read first number
cout << "\nEnter op1 (in the format of p/q):";
p_q1.input();
p_q1.result();

       //read second number
cout << "\nEnter op2 (in the format of p/q):";
p_q2.input();
//Debug line
p_q2.result();

//third rational variable to pass the two rational numbers to the sum function
pq.sum(p_q1, p_q2);

cout << "\nThe sum of op1 and op2 is:";
pq.result();
//ouptput the result of the two rational numbers passed

cout << endl;

cout << "\nTry again (Y/N)?";
cin >> answer;
       cin.ignore(256,'\n'); //to flush the buffer from storing unnecessary/garbage values

} while (answer == 'y' || answer == 'Y');

//testing getters
cout << "\nLast output's numerator is: " << pq.get_Numerator() << endl;
cout << "\nLast output's denominator is: " << pq.get_Denominator() << endl;

return 0;
}


//Implementation of class member functions

//default constructor - The constructor sets the rational number's numerator to 0, and denominator to 1
Addition_Rational::Addition_Rational()
{
numerator = 0;
denominator = 1;
}

//single parameterized constructor - The constructor sets the rational number's numerator to the given parameter and sets the denominator to 1.
Addition_Rational::Addition_Rational(int i)
{
numerator = i;
denominator = 1;
}

//this constructor uses the two values to initialize the rational number's numerator and denominator respectively.
Addition_Rational::Addition_Rational(int p, int q)
{
numerator = p;
denominator = q;
}

//function for addition of op1 and op2
void Addition_Rational::sum(Addition_Rational p_q1, Addition_Rational p_q2)
{
int num = (p_q1.numerator*p_q2.denominator + p_q1.denominator*p_q2.numerator);
int den = (p_q1.denominator*p_q2.denominator);
numerator = num;
denominator = den;
}

void Addition_Rational::input()
{
string in;
int num, den;

getline(cin, in);
int indx = in.find("/");   //finding the position of "/" to separate numerator and denominator
num = atoi(in.substr(0, indx).c_str());   //numerator separated from the rational number
den = atoi(in.substr(indx+1, in.length()).c_str());   //denominator separated from the rational number
numerator = num;
denominator = den;
}

void Addition_Rational::result()
{
cout << numerator << "/" << denominator;
}

// Two getter functions
int Addition_Rational::get_Numerator()
{
return numerator;
}

int Addition_Rational::get_Denominator()
{
return denominator;
}

========================

OUTPUT:


Related Solutions

Define a class called Rational for rational numbers. Arational number is a number that can...
Define a class called Rational for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, /2, 3/4, 64/2, and so forth are all rational numbers.Represent rational numbers as two private values of type int, numfor the numerator and den for the denominator. The class has a default constructor with default values (num = 0,den = 1), a copy constructor, an assignment operator and three friend functions for operator overloading...
C++ make a rational class that includes these members for rational -private member variables to hold...
C++ make a rational class that includes these members for rational -private member variables to hold the numerator and denominator values -a default constructor -an overloaded constructor that accepts 2 values for an initial fraction -member fractions add(), sub(), mul(), div(), less(), eq(), and neq() (less should not return true if the object is less than argument) -a member function that accepts an argument of type of ostream that writes the fraction to that open output stream do not let...
Must be coded in C#. 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic...
Must be coded in C#. 10.8 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write an app to test your class. Use integer variables to represent the private instance variables of the class—the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it’s declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 1/2 and would be stored in the object...
Is rational number divided by an irrational number equal to irrational number or rational number?
Is rational number divided by an irrational number equal to irrational number or rational number? for example such as ( 5 / 2pi )
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter)...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter) for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the class-the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For...
ASAP (Use BigInteger for the Rational class) Redesign and implement the Rational class in Listing 13.13...
ASAP (Use BigInteger for the Rational class) Redesign and implement the Rational class in Listing 13.13 using BigInteger for the numerator and denominator. Use the code at https://liveexample.pearsoncmg.com/test/Exercise13_15Test.txt to test your implementation. Here is a sample run: Sample Run Enter the first rational number: 3 454 Enter the second second number: 7 2389 3/454 + 7/2389 = 10345/1084606 3/454 - 7/2389 = 3989/1084606 3/454 * 7/2389 = 21/1084606 3/454 / 7/2389 = 7167/3178 7/2389 is 0.0029300962745918793 Class Name: Exercise13_15 If...
C++: Write a student class for the library, which have the following: Username, password, Maximum number...
C++: Write a student class for the library, which have the following: Username, password, Maximum number of copies that a student is allowed to keep(less than 5), maximum borrow periods(less than 30 days per book), list of copy(array) cpp and h
WRITE IN C++ Add to the Coord class Edit the provided code in C++ Write a...
WRITE IN C++ Add to the Coord class Edit the provided code in C++ Write a member function named      int distance2origin() that calculates the distance from the (x, y, z) point to the origin (0, 0, 0) the ‘prototype’ in the class definition will be      int distance2origin() outside the class definition             int Coord :: distance2origin() {                         // your code } _______________________________________________________________________________________________________ /************************************************** * * program name: Coord02 * Author: * date due: 10/19/20 * remarks:...
Write a c++ code: 2.2.1 Vehicle Class The vehicle class is the parent class of a...
Write a c++ code: 2.2.1 Vehicle Class The vehicle class is the parent class of a derived class: locomotive. Their inheritance will be public inheritance so react that appropriately in their .h les. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +setName(s:string):void +getName():string +getMap():char** +getSize():int +setMap(s: string):void +getMapAt(x:int, y:int):char +vehicle() +operator--():void +determineRouteStatistics()=0:void The class variables are as follows: map: A 2D array of chars, it will...
In Python Write a Fibonacci class to calculate next number in the 'Fibonacci' class by the...
In Python Write a Fibonacci class to calculate next number in the 'Fibonacci' class by the 'nxt' method. In this class, the 'val' member is a Fibonacci number. The 'nxt' method will return a 'Fibonacci' object whose value is the next number in Fibonacci series. class Fibonacci (): """A Fibonacci number. >>>a = Fibonacci(): >>>a 0 >>>a.nxt() 1 >>>a.nxt().nxt() 1 >>>a.nxt().nxt().nxt() 2 >>>a.nxt().nxt().nxt().nxt() 3 >>>a.nxt().nxt().nxt().nxt().nxt() 5 >>>a.nxt.nxt().nxt().nxt().nxt().nxt() 8 """ def __init__(self): self.val = 0 def nxt(self): """YOUR SOURCE CODE HERE"""...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT