Question

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

C++

1st)

  1. [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 with any legal values. You should provide the following three constructors:

    1. A constructor to make rational objects without any argument. The constructor sets the rational object’s numerator to 0, and denominator to 1.

    2. A 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. A constructor to make rational objects out of a single int value, 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.

    You should also provide the following member functions:
    • An input function that reads from standard input the value for the current object. The input

      should be in the form of 2/3 or 27/51.

    • 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.

    • Two getter functions that return the numerator and denominator respectively.

    • 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: (1) a/b + c/d = (a ∗ d + b ∗ c)/(b ∗ d)

The following code segment demonstrates the usage of the above-mentioned member functions and constructors. Your main function should look something like this:

Rational a(1,2); // a is 1/2
a.output();    // display a on standard output as 1/2
Rational b(2); // b is 2/1
b.output();   // display b on standard output as 2/1
Rational c;   // the default constructor is called to initialize c to 0/1
c.output();  // You can see how the default constructor initializes member variables...
c.input();    // read value for c from input. If the user enters 3/4, then
              // c’s numerator is set to 3, and its denominator is set to 4
c.output();   // display c’s value
//Now testing the Sum function
c.sum(a,b);   // c will be set to 1/2+2/1 = 5/2, see formula above
c.output();   // it should display 5/2

2nd)

[Note: This assignment is adapted from programming project #2 in Savitch, Chapter 11.]

Extend the Rational class by overloading the following operators:

-, *, /, >, <, >=, <=, ==,and!=.

In addition, overload the input operator >> and the output operator << . Numbers are to be input and output in the form 1/2, 15/32, 300/401, and so forth. Note that the numerator, the denominator, or both may contain a minus sign, so -1/2, 15/32, -300/-401 are all possible inputs. The overloaded input and output operators should work with both cin/cout and file stream objects.

Include a function to normalize the values stored so that, after normalization, the denominator is positive and the numerator and denominator are as small as possible. For example, after nor- malization 4/-8 would be represented the same as -1/2.

Write a test program to test your class. Make sure your test program tests all of the operators and member functions. Submit your test program on Blackboard.

To implement your normalization function, you might find it helpful to use the following function to compute the greatest common divisor (see next page):

// Returns the greatest common divisor of m and n.
// Uses the function int abs(int) which is declared in cstdlib.
int gcd(int m, int n)
{

int t;
m = abs(m); n = abs(n); if(n

    t = m;
    m = n;
    n = t;
// don’t care about signs.
// make m >= n so algorithm will work!
    }
    int r;
    r = m % n;
    while (r != 0)
    {
        r = m % n;
        m = n;
        n = r;

}

return m; }

The program should be in C++. Answer the second program as the two problems go hand in hand.

this is the code for the 1st part :

#include <iostream>
#include <cstdlib>


class Rational {
    public:
    // Constructors
        Rational();
        Rational(int num, int den);
        Rational(int num);

    // Member functions
        bool input();
        void output();
        int get_numerator();
        int get_denominator();
        void sum(const Rational &a, const Rational &b);

    private:
        int numerator;
        int denominator;
};


int main(int argc, char *argv[])
{
    using namespace std;
    Rational a(1,2);
    cout << "The rational number a(1,2):\n";
    a.output();
    Rational b(2);
    cout << "The rational number b(2):\n";
    b.output();
    Rational c;
    cout << "The default rational number:\n";
    c.output();
    if (!c.input())
    {
        cout << "Invalid rational number." << endl;
        exit(1);
    }
    c.output();

    cout << "The sum of 1/2 + 2/1 = 5/2:\n";
    c.sum(a,b);
    c.output();

    return 0;
}

//=====================================================================
//
//         Member function definitions
//
//=====================================================================

// Default constructor: creates the rational number 0/1
Rational::Rational()
{
    numerator = 0;
    denominator = 1;
}

// Overloaded constructor: creates rational number num / den
// Constructor calls exit(1) if den == 0 (can't divide by zero)
Rational::Rational(int num, int den)
{
    if (den)
    {
        numerator = num;
        denominator = den;
    }
    else
    {
        std::cout << "Illegal rational number: cannot have 0 in denominator."
            << std::endl;
        exit(1);
    }
}

// Constructor for a rational number entered as an int
Rational::Rational(int num)
{
    numerator = num;
    denominator = 1;
}

int Rational::get_numerator()
{
    return numerator;
}

int Rational::get_denominator()
{
    return denominator;
}

// Input a rational number.
// Returns true if a valid rational number in the form n/m was entered,
// false otherwise.
bool Rational::input()
{
    char op;
    std::cout << "Enter a rational number in the form n/m (n, m are ints): ";
    std::cin >> numerator;
    std::cin >> op;
    std::cin >> denominator;

    if (op != '/' || denominator == 0)
        return false;
    
    return true;
}

void Rational::output()
{
    std::cout << numerator << '/' << denominator << std::endl;
    return;
}

// Sum two rational numbers.
// Sets this rational object to the sum of a + b.
void Rational::sum(const Rational &a, const Rational &b)
{
    numerator = a.numerator * b.denominator + a.denominator * b.numerator;
    denominator = a.denominator * b.denominator;
    return;
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: Could you plz go through this code and let me know if u need any changes in this.Thank You
_________________

#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
using namespace std;


class Rational {
public:
// Constructors
Rational();
Rational(int num, int den);
Rational(int num);

// Member functions
bool input();
void output();
int get_numerator();
int get_denominator();
void sum(const Rational &a, const Rational &b);
  
Rational operator+(const Rational& f) const; // operator+()
Rational operator-(const Rational& f) const; // operator-()
Rational operator*(const Rational& f) const; // operator*()
Rational operator/(const Rational& f) const; // operator*()
bool operator!=(const Rational& f) const; // operator!=()
bool operator==(const Rational& f) const; // operator==()
bool operator<=(const Rational& f) const; // operator<=()
bool operator>=(const Rational& f) const; // operator>=()
bool operator<(const Rational& f) const; // operator<()
bool operator>(const Rational& f) const; // operator>()

Rational normalize();
int gcd(int x, int y) ;


private:
int numerator;
int denominator;
};

int Rational::gcd(int x, int y) {
while (y != 0) {
int temp = x % y;
x = y;
y = temp;
}
return x;
}
Rational Rational::normalize() {

int num = this->numerator;
int den = this->denominator;
if (num < 0 && den < 0) {
num = num * -1;
den = den * -1;
} else if (den < 0) {
num = num * -1;
den = den * -1;
}
int g=gcd(num,den);
  
Rational r(num/g, den/g);
return r;
}

Rational Rational::operator+(const Rational& f) const
{

int a = numerator;
int b = denominator;
int c = f.numerator;
int d = f.denominator;
int sumnumer = (a * d + b * c);
int denom = (b * d);
Rational frac(sumnumer,denom);
frac=frac.normalize();
return frac;
}
Rational Rational::operator-(const Rational& f) const
{
  
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
int subnumer = (a * d - b * c);
int denom = (b * d);
Rational frac(subnumer,denom);
frac=frac.normalize();
return frac;
}
Rational Rational::operator*(const Rational& f) const
{
  
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
int mulnumer = (a * c);
int muldenom = (b * d);
Rational frac(mulnumer,muldenom);
frac=frac.normalize();
return frac;
}
Rational Rational::operator/(const Rational& f) const
{

int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
int divnumer = (a * d);
int divdenom = (c * b);
Rational frac(divnumer,divdenom);
frac=frac.normalize();
return frac;
}

bool Rational::operator<=(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;

if ((n1 / d1) <= (n2 / d2))
return true;
else
return false;
}
bool Rational::operator>=(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;

if ((n1 / d1) >= (n2 / d2))
return true;
else
return false;
}
bool Rational::operator<(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;

if ((n1 / d1) < (n2 / d2))
return true;
else
return false;
}
bool Rational::operator>(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;
if ((n1 / d1) > (n2 / d2))
return true;
else
return false;
}

bool Rational::operator!=(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;

if ((n1 != n2) || (d1 != d2))
return true;
else
return false;
}
bool Rational::operator==(const Rational& f) const
{
int a = this->numerator;
int b = this->denominator;
int c = f.numerator;
int d = f.denominator;
double n1 = a * d;
double d1 = b * d;
double n2 = c * b;
double d2 = d * b;
  
if ((n1 == n2) && (d1 == d2))
return true;
else
return false;
}

int main(int argc, char *argv[])
{
using namespace std;
Rational a(1,2);
cout << "The rational number a(1,2):\n";
a.output();
Rational b(2);
cout << "The rational number b(2):\n";
b.output();
Rational c;
cout << "The default rational number:\n";
c.output();
if (!c.input())
{
cout << "Invalid rational number." << endl;
exit(1);
}
c.output();

cout << "The sum of 1/2 + 2/1 = 5/2:\n";
c.sum(a,b);
c.output();
  
cout<<endl;
Rational f1(3,4),f2(5,6),result;

result = f1 + f2;
f1.output();
cout << "+";
f2.output();
cout << "=";
result.output();
cout<<endl;
result = f1 - f2;
f1.output();
cout << "-";
f2.output();
cout << "=";
result.output();
cout<<endl;
result = f1 * f2;
f1.output();
cout << "*";
f2.output();
cout << "=";
result.output();
cout<<endl;
result = f1 / f2;
f1.output();
cout << "/";
f2.output();
cout << "=";
result.output();
cout<<endl;

bool boolean = f1 < f2;
if (boolean)
{
   f1.output();
       cout<< " is less than ";
       f2.output();
       cout<< endl;
   }
else
{
   f1.output();
       cout<< " is not less than ";
       f2.output();
       cout<< endl;
   }
  
boolean = f1 > f2;
if (boolean)
{
   f1.output();
       cout<< " is greater than ";
       f2.output();
       cout<< endl;
}
else
{
   f1.output();
       cout<< " is not greater than ";
       f2.output();
       cout<< endl;
   }
  
boolean = f1 <= f2;
if (boolean)
{
   f1.output();
       cout<<" is less than or equal to ";
       f2.output();
       cout<< endl;   
   }
else
{
       f1.output();
       cout<<" is not less than or equal to ";
       f2.output();
       cout<< endl;   
         
   }
  
boolean = f1 >= f2;
if (boolean)
{
       f1.output();
       cout<<" is greater than or equal to ";
       f2.output();
       cout<< endl;   
   }
else
{
           f1.output();
       cout<<" is not greater than or equal to ";
       f2.output();
       cout<< endl;   
      
   }
  
boolean = f1 == f2;
if (boolean)
{
               f1.output();
       cout<<" is equal to ";
       f2.output();
       cout<< endl;
   }
else
{
          f1.output();
       cout<<" is not equal to ";
       f2.output();
       cout<< endl;
   }
  
boolean = f1 != f2;
if (boolean)
{
   f1.output();
       cout<<" is not equal to ";
       f2.output();
       cout<< endl;
   }
else
{
       f1.output();
       cout<<" is equal to ";
       f2.output();
       cout<< endl;
      
   }
  

return 0;
}

//=====================================================================
//
// Member function definitions
//
//=====================================================================

// Default constructor: creates the rational number 0/1
Rational::Rational()
{
numerator = 0;
denominator = 1;
}

// Overloaded constructor: creates rational number num / den
// Constructor calls exit(1) if den == 0 (can't divide by zero)
Rational::Rational(int num, int den)
{
if (den)
{
numerator = num;
denominator = den;
}
else
{
std::cout << "Illegal rational number: cannot have 0 in denominator."
<< std::endl;
exit(1);
}
}

// Constructor for a rational number entered as an int
Rational::Rational(int num)
{
numerator = num;
denominator = 1;
}

int Rational::get_numerator()
{
return numerator;
}

int Rational::get_denominator()
{
return denominator;
}

// Input a rational number.
// Returns true if a valid rational number in the form n/m was entered,
// false otherwise.
bool Rational::input()
{
char op;
std::cout << "Enter a rational number in the form n/m (n, m are ints): ";
std::cin >> numerator;
std::cin >> op;
std::cin >> denominator;

if (op != '/' || denominator == 0)
return false;
  
return true;
}

void Rational::output()
{
std::cout << numerator << '/' << denominator;
return;
}

// Sum two rational numbers.
// Sets this rational object to the sum of a + b.
void Rational::sum(const Rational &a, const Rational &b)
{
numerator = a.numerator * b.denominator + a.denominator * b.numerator;
denominator = a.denominator * b.denominator;
return;
}

___________________________

Output:

______________________Thank You

Add a comment
Know the answer?
Add Answer to:
C++ 1st) [Note: This assignment is adapted from programming project #7 in Savitch, Chapter 10, p.616.]...
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
  • Having to repost this as the last answer wasn't functional. Please help In the following program...

    Having to repost this as the last answer wasn't functional. Please help In the following program written in C++, I am having an issue that I cannot get the reducdedForm function in the Rational.cpp file to work. I cant figure out how to get this to work correctly, so the program will take what a user enters for fractions, and does the appropriate arithmetic to the two fractions and simplifies the answer. Rational.h class Rational { private: int num; int...

  • 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...

  • 13.21 Lab: Rational class This question has been asked here before, but every answer I have...

    13.21 Lab: Rational class This question has been asked here before, but every answer I have tested did not work, and I don't understand why, so I'm not able to understand how to do it correctly. I need to build the Rational.cpp file that will work with the main.cpp and Rational.h files as they are written. Rational Numbers It may come as a bit of a surprise when the C++ floating-point types (float, double), fail to capture a particular value...

  • C++ CODE /* This is program project 2 on page 695. * Before you begin the...

    C++ CODE /* This is program project 2 on page 695. * Before you begin the project, please read the project description * on page 695 first. * * Author: Your Name * Version: Dates */ #include <iostream> #include <cmath> #include <cassert> using namespace std; class Fraction { public: // constructor Fraction(int a, int b); // generate a fraction which is a/b Fraction(int a); // generate a fraction which is a/1 Fraction(); // generate a fraction which is 0/1. i.e...

  • C++ CODE /* This is program project 2 on page 695. * Before you begin the...

    C++ CODE /* This is program project 2 on page 695. * Before you begin the project, please read the project description * on page 695 first. * * Author: Your Name * Version: Dates */ #include <iostream> #include <cmath> #include <cassert> using namespace std; class Fraction { public: // constructor Fraction(int a, int b); // generate a fraction which is a/b Fraction(int a); // generate a fraction which is a/1 Fraction(); // generate a fraction which is 0/1. i.e...

  • In the following code, it gets hung up at    cout << "Number1 * Number2 =...

    In the following code, it gets hung up at    cout << "Number1 * Number2 = " << number1 * number2 << endl; giving an error of "no math for operator<<" what am i doing wrong? Thank you #include <iostream> #include <cctype> #include <cstdlib> using namespace std; class Rational //class for rational numbers (1/2, 5/9, ect..) {    public:        Rational(int numerator, int denominator);        Rational(int numberator);        Rational(); //default        friend istream& operator >>(istream& ins,...

  • C++ Object Oriented assignment Can you please check the program written below if it has appropriately...

    C++ Object Oriented assignment Can you please check the program written below if it has appropriately fulfilled the instructions provided below. Please do the necessary change that this program may need. I am expecting to get a full credit for this assignment so put your effort to correct and help the program have the most efficient algorithm within the scope of the instruction given. INSTRUCTIONS Create a fraction class and add your Name to the name fraction and use this...

  • 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...

  • Please use C++ and add comments to make it easier to read. Do the following: 1)...

    Please use C++ and add comments to make it easier to read. Do the following: 1) Add a constructor with two parameters, one for the numerator, one for the denominator. If the parameter for the denominator is 0, set the denominator to 1 2) Add a function that overloads the < operator 3) Add a function that overloads the * operator 4) Modify the operator<< function so that if the numerator is equal to the denominator it just prints 1...

  • Hello, I'm looking to modify my fraction program to include constructors and destructors. Here are all...

    Hello, I'm looking to modify my fraction program to include constructors and destructors. Here are all the instructions: Create constructors default two argument three argument copy constructor Create a destructor. The destructor should set whole and numerator to zero and denominator to one. Add cout statements to the constructors and the destructor so you know when it's getting executed. Add system ("pause") to the destructor so you know when it executes. Only positive values allowed If denominator is 0 set...

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