Question

In: Computer Science

Wondering where to start on this C++ homework assignment involving friend functions and overloading operators implemented...

Wondering where to start on this C++ homework assignment involving friend functions and overloading operators implemented in a Rational class. These are the instructions:

Your class will need to store two internal, integer values for each Rational number, the numerator (top) and denominator (bottom) of the fraction. It will have three constructor functions, with zero, one and two arguments, used as follows:

    Rational test1, test2(10), test3(1, 2);

The declaration for test1 calls the default (no argument) constructor, which should set the value to 0. (Like any other whole number, zero will have a 1 in the denominator: we cannot divide by zero.) The declaration for test2 calls a constructor with one argument. The value for test2 will be 10, stored as 10 on the top and 1 on the bottom. The declaration for test3 calls the constructor with two arguments. test3 is equal to 0.5, with 1 on the top and 2 on the bottom.

All of the operators required in the problem should be provided for the Rational class as overloaded, Friend functions. In general, you should be able to execute code such as following:

// Display the three values to test cout
    cout << "\nTest1 equals " << test1;
    cout << "\nTest2 equals " << test2;
    cout << "\nTest3 equals " << test3;
// Test our operators
    cout << "\nTest1 * Test2 equals " << test1*test2;
    cout << "\nTest1 / Test3 equals " << test1/test3;
    cout << "\nTest2 + Test3 equals " << test2+test3;
    cout << "\nTest3 - Test1 equals " << test3-test1;
    if (test1 == test2)
        cout << "\nTest1 is equal to Test2";
    if (test1 < test2)
        cout << "\nTest1 is less than Test2";

and so on until you test all the implemented member functions and Friend functions of the Rational class.

This is what I have so far


#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <time.h>

class Rational
{
    private:
        int numerator;
        int denominator;
        void reduce();

    public:
        Rational();
        Rational(int n, int d);
        int getNumerator();
        int getDenominator();
        void add(Rational addend);
        void sub(Rational subtractor);
        void mul(Rational multiplicand);
        void div(Rational dividend);
        int greatestCommonDenominator(int a,int b);
        bool less(Rational comparator);
        bool eq(Rational comparator);
        bool neq(Rational comparator);
        void output(std::ostream& oss);
};

Rational::Rational() {
   numerator = 0;
   denominator = 1;
}

Rational::Rational(int n, int d) {
//   cout<<"Creating rational number "<<n<<"/"<<d<<endl;
   numerator = n;
   denominator = d;

   if (numerator < 0 and denominator < 0) {
       numerator = -numerator;
       denominator = - denominator;
   }
   if (numerator*denominator < 0) {
       cout<<"Error negative fraction"<<std::endl;
       exit(1);
   }
}
int Rational::getNumerator() {
   return numerator;
}
int Rational::getDenominator() {
   return denominator;
}
int Rational::greatestCommonDenominator(int a, int b) {
   //cout<<"Finding greatest common denominator of "<<a<<" and "<<b<<endl;
   int gcd = 1;
   int smallerNum = a;
   if ( a > b ) {
       smallerNum = b;
   }
   for ( int i = 1; i <= smallerNum; i++ ) {
       if (((a % i) == 0) and ((b % i) == 0)) {
           gcd = i;
       }
   }
   //cout<<"Greatest common denominator is "<<gcd<<endl;
   return gcd;
}
void Rational::reduce() {
   int gcd = greatestCommonDenominator(numerator, denominator);
   numerator = numerator / gcd;
   denominator = denominator / gcd;
}

void Rational::add(const Rational addend) {
   numerator = numerator*addend.denominator + addend.numerator*denominator;
   denominator = denominator*addend.denominator;
   reduce();
   return;
}
void Rational::sub(Rational subtractor) {
   numerator = numerator*subtractor.denominator - subtractor.numerator*denominator;
   denominator = denominator*subtractor.denominator;
   if ( numerator < 0 ) {
       cout<<"Error - negative fraction"<<std::endl;
   }
   reduce();
   return;

}
void Rational::mul(Rational multiplicand) {
   numerator *= multiplicand.numerator;
   denominator *= multiplicand.denominator;
   reduce();
}

void Rational::div(Rational dividend) {
   denominator *= dividend.numerator;
   numerator *= dividend.denominator;
   reduce();
}

bool Rational::less(Rational comparator) {
   return (numerator*comparator.denominator < comparator.numerator*denominator);
}

bool Rational::eq(Rational comparator) {
   return (numerator*comparator.denominator == comparator.numerator*denominator);
}

bool Rational::neq(Rational comparator) {
   return !eq(comparator);
}

void Rational::output(std::ostream& oss) {
   oss<<numerator<<"/"<<denominator<<std::endl;
}

int main() {
   Rational fraction1(1,2);
   Rational fraction2(2,4);

   fraction1.add(fraction2);
   fraction1.sub(fraction2);
   if (fraction1.eq(fraction2)) {
       cout<<"Add and eq work great"<<endl;
   }
   cout<<"Just checking"<<endl;
   fraction1.output(cout);
   fraction2.output(cout);
   //insert any test code for Rational class
   return (0);
}

Solutions

Expert Solution

#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <time.h>

class Rational
{
private:
int numerator;
int denominator;
void reduce();

public:
Rational();
Rational(int n); // add constructor that takes only numerator
Rational(int n, int d);
int getNumerator();
int getDenominator();
void add(Rational addend);
void sub(Rational subtractor);
void mul(Rational multiplicand);
void div(Rational dividend);
int greatestCommonDenominator(int a,int b);
bool less(Rational comparator);
bool eq(Rational comparator);
bool neq(Rational comparator);
void output(std::ostream& oss);

friend Rational operator +(const Rational &r1, const Rational &r2);
friend Rational operator -(const Rational &r1, const Rational &r2);
friend Rational operator *(const Rational &r1, const Rational &r2);
friend Rational operator /(const Rational &r1, const Rational &r2);

friend bool operator ==(const Rational &r1, const Rational &r2);
friend bool operator !=(const Rational &r1, const Rational &r2);
friend bool operator <(const Rational &r1, const Rational &r2);
friend bool operator >(const Rational &r1, const Rational &r2);
friend bool operator <=(const Rational &r1, const Rational &r2);
friend bool operator >=(const Rational &r1, const Rational &r2);

friend std::ostream& operator <<(std::ostream &outs, const Rational &r);
friend std::istream& operator >>(std::istream &ins, Rational &r);
};

Rational::Rational() {
numerator = 0;
denominator = 1;
}

Rational::Rational(int n)
{
numerator = n; // set numerator to n
denominator = 1; // set denominator to 1
}

Rational::Rational(int n, int d) {
// cout<<"Creating rational number "<<n<<"/"<<d<<endl;
numerator = n;
denominator = d;

if (numerator < 0 and denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
if (numerator*denominator < 0) {
std::cout<<"Error negative fraction"<<std::endl;
exit(1);
}
}
int Rational::getNumerator() {
return numerator;
}
int Rational::getDenominator() {
return denominator;
}
int Rational::greatestCommonDenominator(int a, int b) {
//cout<<"Finding greatest common denominator of "<<a<<" and "<<b<<endl;
int gcd = 1;
int smallerNum = a;
if ( a > b ) {
smallerNum = b;
}
for ( int i = 1; i <= smallerNum; i++ ) {
if (((a % i) == 0) and ((b % i) == 0)) {
gcd = i;
}
}
//cout<<"Greatest common denominator is "<<gcd<<endl;
return gcd;
}

void Rational::reduce() {
int gcd = greatestCommonDenominator(numerator, denominator);
numerator = numerator / gcd;
denominator = denominator / gcd;
}

void Rational::add(const Rational addend) {
numerator = numerator*addend.denominator + addend.numerator*denominator;
denominator = denominator*addend.denominator;
reduce();
return;
}
void Rational::sub(Rational subtractor) {
numerator = numerator*subtractor.denominator - subtractor.numerator*denominator;
denominator = denominator*subtractor.denominator;
if ( numerator < 0 ) {
std::cout<<"Error - negative fraction"<<std::endl;
}
reduce();
return;

}
void Rational::mul(Rational multiplicand) {
numerator *= multiplicand.numerator;
denominator *= multiplicand.denominator;
reduce();
}

void Rational::div(Rational dividend) {
denominator *= dividend.numerator;
numerator *= dividend.denominator;
reduce();
}

bool Rational::less(Rational comparator) {
return (numerator*comparator.denominator < comparator.numerator*denominator);
}

bool Rational::eq(Rational comparator) {
return (numerator*comparator.denominator == comparator.numerator*denominator);
}

bool Rational::neq(Rational comparator) {
return !eq(comparator);
}

void Rational::output(std::ostream& oss) {
oss<<numerator<<"/"<<denominator<<std::endl;
}

// overloaded operators as friend functions
Rational operator +(const Rational &r1, const Rational &r2)
{
Rational r(r1.numerator*r2.denominator + r2.numerator*r1.denominator, r1.denominator*r2.denominator);
r.reduce();
return r;
}

Rational operator -(const Rational &r1, const Rational &r2)
{
Rational r(r1.numerator*r2.denominator - r2.numerator*r1.denominator, r1.denominator*r2.denominator);
r.reduce();
return r;
}

Rational operator *(const Rational &r1, const Rational &r2)
{
Rational r(r1.numerator*r2.numerator, r1.denominator*r2.denominator);
r.reduce();
return r;
}

Rational operator /(const Rational &r1, const Rational &r2)
{
Rational r(r1.numerator*r2.denominator , r1.denominator*r2.numerator);
r.reduce();
return r;
}

bool operator ==(const Rational &r1, const Rational &r2)
{
return (r1.numerator*r2.denominator == r2.numerator*r1.denominator);
}

bool operator !=(const Rational &r1, const Rational &r2)
{
return !(r1 == r2);
}

bool operator <(const Rational &r1, const Rational &r2)
{
return (r1.numerator*r2.denominator < r2.numerator*r1.denominator);
}

bool operator >(const Rational &r1, const Rational &r2)
{
return (r1.numerator*r2.denominator > r2.numerator*r1.denominator);
}

bool operator <=(const Rational &r1, const Rational &r2)
{
return (r1.numerator*r2.denominator <= r2.numerator*r1.denominator);
}

bool operator >=(const Rational &r1, const Rational &r2)
{
return (r1.numerator*r2.denominator >= r2.numerator*r1.denominator);
}

// overloaded stream insertion operator
std::ostream& operator <<(std::ostream &outs, const Rational &r)
{
outs<<r.numerator<<"/"<<r.denominator;
return outs;
}

// overloaded stream extraction operator
std::istream& operator >>(std::istream &ins, Rational &r)
{
char sep;

// reads the rational number in the format numerator/denominator
ins>>r.numerator>>sep>>r.denominator;
return ins;
}

int main() {
Rational fraction1(1,2);
Rational fraction2(2,4);

fraction1.add(fraction2);
fraction1.sub(fraction2);
if (fraction1.eq(fraction2)) {
std::cout<<"Add and eq work great"<<std::endl;
}

std::cout<<"Just checking"<<std::endl;
fraction1.output(std::cout);
fraction2.output(std::cout);
//insert any test code for Rational class
Rational test1, test2(10), test3(1, 2);
// Display the three values to test cout
std::cout << "\nTest1 equals " << test1;
std::cout << "\nTest2 equals " << test2;
std::cout << "\nTest3 equals " << test3;
// Test our operators
std::cout << "\nTest1 * Test2 equals " << test1*test2;
std::cout << "\nTest1 / Test3 equals " << test1/test3;
std::cout << "\nTest2 + Test3 equals " << test2+test3;
std::cout << "\nTest3 - Test1 equals " << test3-test1;
if (test1 == test2)
std::cout << "\nTest1 is equal to Test2";
if (test1 < test2)
std::cout << "\nTest1 is less than Test2";
return (0);
}

//end of program

Output:


Related Solutions

C++ Programming 19.2 Operator Overloading practice Write the prototypes and functions to overload the given operators...
C++ Programming 19.2 Operator Overloading practice Write the prototypes and functions to overload the given operators in the code main.cpp //This program shows how to use the class rectangleType. #include <iostream> #include "rectangleType.h" using namespace std; int main() { rectangleType rectangle1(23, 45); //Line 1 rectangleType rectangle2(12, 10); //Line 2 rectangleType rectangle3; //Line 3 rectangleType rectangle4; //Line 4 cout << "Line 5: rectangle1: "; //Line 5 rectangle1.print(); //Line 6 cout << endl; //Line 7 cout << "Line 8: rectangle2: "; //Line...
Overloading the insertion (<<) and extraction (>>) operators for class use requires creating operator functions that...
Overloading the insertion (<<) and extraction (>>) operators for class use requires creating operator functions that use these symbols but have a parameter list that includes a class ____. object address reference data type Flag this Question Question 210 pts When overloading the insertion operator to process a Complex object, it’s important to understand that you’re overloading an operator in the ____ class. istream operator Complex ostream Flag this Question Question 310 pts ____ class variables are allocated memory locations...
C++ Please Fill in for the functions for the code below. The functions will be implemented...
C++ Please Fill in for the functions for the code below. The functions will be implemented using vectors ONLY. Additional public helper functions or private members/functions can be used. The List class will be instantiated via a pointer and called similar to the code below: Stack *ptr = new Stack(); ptr->push(value); int pop1 = ptr->pop(); int pop2 = ptr->pop(); bool isEmpty = ptr->empty(); class Stack{     public: // Default Constructor Stack() {// ... } // Push integer n onto top of...
C++ Please Fill in for the functions for the code below. The functions will be implemented...
C++ Please Fill in for the functions for the code below. The functions will be implemented using vectors. Additional public helper functions or private members/functions can be used. The List class will be instantiated via a pointer and called similar to the code below: ---the code can be general (can be tested with any int main() test function)--- Stack *ptr = new Stack(); ptr->push(value); int pop1 = ptr->pop(); int pop2 = ptr->pop(); bool isEmpty = ptr->empty(); class Stack{     public: //...
In this homework assignment, you will be writing three `void` functions. These functions each take a...
In this homework assignment, you will be writing three `void` functions. These functions each take a single integer parameter. The functions accomplish the following tasks. * The first function prints out the sum of the numbers from 1 up to and including the number passed to it as an argument. * The second function prints out the sum of the even numbers from 2 up to and including the number passed to it as an argument. * The third function...
Assignment Write each of the following functions. The function header must be implemented exactly as specified....
Assignment Write each of the following functions. The function header must be implemented exactly as specified. Write a main function that tests each of your functions. Specifics In the main function ask for a filename and fill a list with the values from the file. Each file should have one numeric value per line. This has been done numerous times in class. You can create the data file using a text editor or the example given in class – do...
Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how...
Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how to overload binary operators as friend functions. Show how to convert from a fundamental type to a user-defined type using a constructor. Understand exception handling mechanisms using try-catch block statements. Understand the Application Complex Numbers A complex number, c, is an ordered pair of real numbers (doubles). For example, for any two real numbers, s and t, we can form the complex number: This...
Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how...
Lab Assignment Objectives 'Be able to overload combined binary operators as member operator functions. Show how to overload binary operators as friend functions. Show how to convert from a fundamental type to a user-defined type using a constructor. Understand exception handling mechanisms using try-catch block statements. Understand the Application Complex Numbers A complex number, c, is an ordered pair of real numbers (doubles). For example, for any two real numbers, s and t, we can form the complex number: This...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects •...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects • Methods • Arrays of Primitive Values • Arrays of Objects • Recursion • for and if Statements • Insertion Sort 2. Use the following Guidelines • Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc). • User upper case for constants. Use title case (first letter is upper case) for classes. Use lower case with uppercase word separators for...
Assignment (C language, not C ++) Start a new project to store grade information for 5...
Assignment (C language, not C ++) Start a new project to store grade information for 5 students using structures. Declare a structure called student_t that contains : First name Last name Student ID Number Percentage grade Letter grade Create the following functions: getStudentInfo(void)- Declares a single student object - Uses printf()/scanf() to get keyboard input for Name, SID, and Percentage (not Letter). - Returns a single student structure calcStudentGrade(student_t *st_ptr)- Takes the pointer to a student (to avoid making a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT