Question

c++ Write a rational number class. A rational number is a number that can be written...

c++

Write a rational number class. A rational number is a number that can be written as p/q where p and q are integers. The division is not carried out, only indicated. Thus you should represent rational numbers by two int values, numerator and denominator.

Constructors must be present to create objects with any legal values. You should provide constructors to make objects out of pairs of int values; that is, a constructor with two int parameters. Since very int is also a rational number, as in 2/1 or 17/1, you should provide a constructor with a single int parameter as well. You should take into account that if the user constructs a rational number that corresponds to a non-reduced fraction, you should automatically “reduce” the fraction in your constructor. For example, if the user constructs a rational number with numerator 4 and denominator 16, you should store it as numerator 1 and denominator 4. You should also take into account the storage of negative values. For simplicity’s sake, always store a negative in the numerator if need be. For example, if the user constructs a rational number with numerator 2 and denominator -4, it should be stored as -1, 2 respectively. In addition, if the user constructs a rational number with numerator -1 and denominator -3, it should be stored as 1, 3 respectively. Lastly, if the user happens to construct a rational number with zero as the denominator, simply change the denominator to 1.

Provide the following public member functions:

add – accepts a rational number parameter and returns a rational number

sub– accepts a rational number parameter and returns a rational number

mul– accepts a rational number parameter and returns a rational number

div– accepts a rational number parameter and returns a rational number

equals– accepts a rational number parameter and returns a bool

less_than– accepts a rational number parameter and returns a bool

greater_than– accepts a rational number parameter and returns a bool

input – accepts an istream parameter and gets input in the form numerator/denominator from the keyboard

output – accepts an ostream parameter and writes rational numbers in the form numerator/denominator or numerator if the denominator is 1, or 0 if the numerator is zero

Provide the following private member functions:

reduce – a void function that accepts no arguments and reduces the rational number

gcd – a function that returns an int and returns the greatest common divisor of its two int parameters num1 and num2 (body given below) – this uses Euclid’s algorithm

   while (num1 != num2)

        if (num1 > num2)

           num1 = num1 - num2;

        else

           num2 = num2 - num1;

     return num1;

using this main for testing:

int main()
{
        ofstream fout;
        fout.open("out.txt");
        RationalNumber op1 = RationalNumber(1, -4);
        op1.output(fout);

        RationalNumber op2 = RationalNumber(5);
        op2.output(fout);
        RationalNumber op3 = RationalNumber(-6, -9);
        op3.output(fout);

        RationalNumber sum = op1.add(op2);
        fout << "sum: ";
        sum.output(fout);


        RationalNumber difference = op2.sub(op3);
        fout << "difference: ";
        difference.output(fout);

        RationalNumber product = op1.mul(op3);
        fout << "product: ";
        product.output(fout);

        RationalNumber quotient = op3.div(op2);
        fout << "quotient: ";
        quotient.output(fout);

        bool lessThan = op1.less_than(op2), greaterThan = op1.greater_than(op3), equalTo = op1.equals(RationalNumber(2, -6)), equalTo2 = op1.equals(op2);

        fout << lessThan << endl;
        fout << greaterThan << endl;
        fout << equalTo << endl;
        fout << equalTo2 << endl;

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Compilation command

g++ RationalNumber.cpp main.cpp -o RationalNumber

main.cpp is the one given in question.

CODE

RationalNumber.cpp

#include "RationalNumber.h"

// Constructor when denom is 1
RationalNumber::RationalNumber(int num) {
   // calling the constructor with numerator and denominator.
   RationalNumber x = RationalNumber(num,1);

   // initializing the member variables.
   numerator = x.numerator;
   denominator = x.denominator;
}
RationalNumber::RationalNumber(int num, int denom = 1) {

   // variable to keep track of negative fractions.
   bool neg = false;

   // if denom is 0 then make it 1
   denom = denom == 0? 1:denom;

  
   // if numerator less than zero then make neg to true.
   if(num < 0) {
       num = -num;
       neg = neg ^ true;
   }
   // if denominator less than zero then make neg to true.
   if(denom < 0) {
       denom = -denom;
       neg = neg ^ true;
   }

   // xor of neg will make it false if both are negative or both +ve

   numerator = num;
   denominator = denom;
   // to simplify we must call the gcd on numerator and denominator.
   int gcdNum = gcd();

   // divide the gcd with numerator and denominator
   if(gcdNum != 0) {
       numerator = numerator/gcdNum;
       denominator = denominator/gcdNum;
   }

   // if the number is negative make numerator negative.
   numerator = neg?-numerator:numerator;

}

int RationalNumber::gcd() {
   int a = numerator;
   int b = denominator;

   int t;

   // Euclidean method to compute gcd
   while(b) {
       t = b;
       b = a%b;
       a = t;
   }
   return a;
}

// adding of two rational numbers
RationalNumber RationalNumber::add(RationalNumber r) {

   // computing numerator.
   int num = numerator * r.denominator + denominator * r.numerator;
   // computing denominator.
   int denom = r.denominator * denominator;

   //constructing new object and returning it
   RationalNumber ans(num,denom);
   return ans;
}

void RationalNumber::output(ofstream out) {
   // if numerator is zero output 0
   if(numerator == 0) {
       out<<0<<endl;
   }
   // if denominator is 1 then just print numerator
   else if(denominator == 1) {
       out<<numerator<<endl;
   }
   // print the fraction.
   else {
       out<<numerator<<"/"<<denominator<<endl;
   }

}

// subtracts two fraction.
RationalNumber RationalNumber::sub(RationalNumber r) {

   // computing numerator.
   int num = numerator * r.denominator - denominator * r.numerator;

   // computing denominator.
   int denom = r.denominator * denominator;

   RationalNumber ans(num,denom);
   return ans;
}

// multiplication of two rational numbers
RationalNumber RationalNumber::mul(RationalNumber r) {

   cout<<r.numerator<< " "<<r.denominator<<endl;
   // computing numerator.
   int num = numerator * r.numerator;
   // computing denominator.
   int denom = r.denominator * denominator;

   RationalNumber ans(num,denom);
   return ans;
}

// division of two rational numbers
RationalNumber RationalNumber::div(RationalNumber r) {

   cout<<r.numerator<< " "<<r.denominator<<endl;
   // computing numerator.
   int num = numerator * r.denominator;
   // computing denominator.
   int denom = r.numerator * denominator;

   RationalNumber ans(num,denom);
   return ans;
}

// check for less than
bool RationalNumber::less_than(RationalNumber r) {
   return (numerator*r.denominator)<(denominator*r.numerator);
}

// check for greater than opposite of less than
bool RationalNumber::greater_than(RationalNumber r) {
   return (numerator*r.denominator)>(denominator*r.numerator);
}

// check for equals
bool RationalNumber::equals(RationalNumber r) {
   return (numerator==r.numerator)&&(denominator==r.denominator);
}

RationalNumber.h

#include <iostream>
#include <fstream>

using namespace std;

// Class declaration of RAtional Number;

class RationalNumber {
   public:
       int numerator;
       int denominator;

       RationalNumber(int num, int denom);
       RationalNumber(int num);
       int gcd();

       RationalNumber add(RationalNumber r);
       RationalNumber sub(RationalNumber r);
       RationalNumber mul(RationalNumber r);
       RationalNumber div(RationalNumber r);

       bool less_than(RationalNumber r);
       bool greater_than(RationalNumber r);
       bool equals(RationalNumber r);

      
       void output(ofstream &out);

  
};

OUTPUT

-1/4
5
2/3
sum: 19/4
difference: 13/3
product: -1/6
quotient: 2/15
1
0
0
0

Thanks,

Add a comment
Know the answer?
Add Answer to:
c++ Write a rational number class. A rational number is a number that can be written...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • Define a class for rational numbers. A rational number is a number that can be represented...

    Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1/2 etc we mean the everyday meaning of the fraction, not the integer division this expression would produce in a C++ program). Represent rational numbers as two values of type int, one for the numerator and one for the denominator. Call the class rational Num...

  • NEED ASAP PLEASE HELP Task: --------------------------------------------------------------------------------------...

    NEED ASAP PLEASE HELP Task: --------------------------------------------------------------------------------------------------------------------------------- Tasks to complete: ---------------------------------------------------------------------------------------------------------------------------------------- given code: ----------------------------------------------------------------------------------------------------------------------------------------------- main.cpp #include <iostream> #include <iomanip> #include "fractionType.h" using namespace std; int main() { fractionType num1(5, 6); fractionType num2; fractionType num3; cout << fixed; cout << showpoint; cout << setprecision(2); cout << "Num1 = " << num1 << endl; cout << "Num2 = " << num2 << endl; cout << "Enter the fraction in the form a / b: "; cin >> num2; cout << endl; cout <<...

  • Define a class for rational numbers. A rational number is a "ratio-nal" number, composed of two...

    Define a class for rational numbers. A rational number is a "ratio-nal" number, composed of two integers with division indicated. Requirement: - two member variables: (int) numerator and (int) denominator. - two constructors: one that takes in both numerator and denominator to construct a rational number, and one that takes in only numerator and initialize the denominator as 1. - accessor/modifier - member functions: add(), sub(), mul(), div(), and less(). Usage: to add rational num b and rational num a,...

  • Rational Number *In Java* A rational number is one that can be expressed as the ratio...

    Rational Number *In Java* A rational number is one that can be expressed as the ratio of two integers, i.e., a number that can be expressed using a fraction whose numerator and denominator are integers. Examples of rational numbers are 1/2, 3/4 and 2/1. Rational numbers are thus no more than the fractions you've been familiar with since grade school. Rational numbers can be negated, inverted, added, subtracted, multiplied, and divided in the usual manner: The inverse, or reciprocal of...

  • C++ and/or using Xcode... Define a class of rational numbers. A rational number is a number...

    C++ and/or using Xcode... Define a class of rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 1/2, 3/4, 64/2, and so forth are all rational numbers. (By 1/2, etc., we mean the everyday meaning of the fraction, not the integer division this expression could produce in a C++ program). Represent rational numbers as two values of type int, one for the numerator and one for the denominator. Call...

  • Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int...

    Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int = 0, int = 1 ); // default constructor Rational addition( const Rational & ) const; // function addition Rational subtraction( const Rational & ) const; // function subtraction Rational multiplication( const Rational & ) const; // function multi. Rational division( const Rational & ) const; // function division void printRational () const; // print rational format void printRationalAsDouble() const; // print rational as...

  • C++ 1st) [Note: This assignment is adapted from programming project #7 in Savitch, Chapter 10, p.616.]...

    C++ 1st) [Note: This assignment is adapted from programming project #7 in Savitch, Chapter 10, p.616.] Write a rational number class. Recall that a rational number is a ratio-nal 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...

  • Redo Programming Exercise 7 of Chapter 7 so that your program handles exceptions such as division...

    Redo Programming Exercise 7 of Chapter 7 so that your program handles exceptions such as division by zero and invalid input. Your program should print Denominator must be nonzero and reprompt for a valid denominator when 0 is entered for a denominator. Please specify what should go in the divisionByZero.h file and the changes made to main.cpp Please provide output. Thank you in advance! main.cpp so far #include <iostream> using namespace std; void addFractions(int num1, int num2, int den1, int...

  • java code Write a class called FractionObject that represents a fraction with an integer numerator and...

    java code Write a class called FractionObject that represents a fraction with an integer numerator and denominator as fields. A Fraction Object object should have the following methods: A constructor with int numerator, int denominator as parameters - Constructs a new fraction object to represent the ratio (numerator/denominator). The denominator cannot be 0, so output a message if O is passed and set the numerator and denominator to 1. A constructor with no parameters - Constructs a new FractionObject to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT