Question

In: Computer Science

C++ Simple Programming Assignment you need to build off of the code below: #include using namespace...

C++ Simple Programming Assignment

you need to build off of the code below:

#include

using namespace std;

// class definition

class Fraction {

        // two data members

        // one representing numerator

        int numerator;

        // other, representing denominator

        int denominator;

        public:

                void set (int numerator, int denominator);

                Fraction addedTo (Fraction f);

                Fraction subtract (Fraction f);

                Fraction multipliedBy (Fraction f);

                Fraction dividedBy (Fraction f);

                bool isEqualTo (Fraction f);

                void print ();

};

void Fraction :: set (int numerator, int denominator) {

        this -> numerator = numerator;

        this -> denominator = denominator;

}

Fraction Fraction :: addedTo (Fraction f)   

        Fraction result;

        result.denominator = (this -> denominator) * f.denominator;

        result.numerator = ((this -> numerator) * f.denominator) + ((this -> denominator) * f.numerator);

        return result;

}

Fraction Fraction :: subtract (Fraction f) {

        Fraction result;

       result.denominator = (this -> denominator) * f.denominator

        result.numerator = ((this -> numerator) * f.denominator) - ((this -> denominator) * f.numerator);

        return result;

}

Fraction Fraction ::multipliedBy (Fraction f) {                                

        Fraction result

        result.numerator = (this -> numerator) * f.numerator;

        result.denominator = (this -> denominator) * f.denominator;

        return result;

}

Fraction Fraction :: dividedBy (Fraction f) {

                                

        Fraction result

        Fraction reciprocal;

        reciprocal.numerator = f.denominator;

        reciprocal.denominator = f.numerator;

        result.numerator = (this -> numerator) * reciprocal.numerator;

        result.denominator = (this -> denominator) * reciprocal.denominator;

        return result;

}

// this function checks if the Fraction argument f is equal to the calling Fraction object

bool Fraction :: isEqualTo (Fraction f) {

      

        if (((this -> numerator) * f.denominator) == ((this -> denominator) * f.numerator)) {

                return true;

        }

        // otherwise

        return false;

}

// this function will print the Fraction in the specified format

void Fraction :: print () {

      

        cout << (this -> numerator) << "/" << (this -> denominator);

}

**and the provided code as well**

Instructions:

  1. earase your set() function. Add two constructors, a default constructor (a constructor that takes no parameters) and a parameterized constructor (a constructor that takes parameters). The default constructor assigns the value 0 to the Fraction. In the parameterized construtor, the first parameter will represent the initial numerator of the Fraction, and the second parameter will represent the initial denominator of the Fraction.
    Since Fractions cannot have denominators of 0, the default constructor should assign 0 to the numerator and 1 to the denominator. Also, the parameterized constructor should check to make sure that the second parameter is not a 0 by using the statement "assert(denominatorParameter != 0);". To use the assert() function you'll also need to #include . (Note, I don't expect the variable to be named "denominatorParameter," that's just my placeholder for the example.)
    assert() is not the best way to handle this, but it will have to do until we study exception handling.

  2. Add the const keyword to your class wherever appropriate (and also make sure to pass objects by reference -- see lesson 15.9). Your class may still work correctly even if you don't do this correctly, so this will require extra care!!

  3. Add a private "simplify()" function to your class and call it from the appropriate member functions. (For most of you there will be 5 places where you need to call it. This, however, depends on how you write the class, so don't assume you are wrong if you don't have exactly 5.) The best way to do this is to make the function a void function with no parameters that reduces the calling object.
    As you can see from the sample output given below, you are still not required to change improper Fractions into mixed numbers for printing. Just print it as an improper Fraction. Make sure that your class will reduce ANY non-negative Fraction, not just the Fractions that are tested in the provided client program. Fractions should not be simply reduced upon output, they should be stored in reduced form at all times. In other words, you should ensure that all Fraction objects are reduced before the end of any member function. You are also not required to deal with negative numbers, either in the numerator or the denominator.
    You must create your own algorithm for reducing Fractions. Don't look up an already existing algorithm for reducing Fractions or finding GCF. The point here is to have you practice solving the problem on your own. In particular, don't use Euclid's algorithm. Don't worry about being efficient. It's fine to have your function check every possible factor, even if it would be more efficient to just check prime numbers. Just create something of your own that works correctly on ANY Fraction.
    Note: this part of the assignment is worth 5 points. If you are having trouble keeping up with the class, I suggest you skip this part and take the 5 point deduction.

  4. insert the client program in a separate file from the class, and divide the class into specification file (fraction.h) and implementation file (fraction.cpp), so your code will be in 3 separate files.

  5. Add documentation to your assignment. Be sure to carefully read section 1D of the Style Conventions, "Commenting in Classes". Hint: in this assignment, it turns out that none of the functions have preconditions.

**Your class is required to (still) have exactly two data members.

***You should copy and paste the client program below, and use it as the client program. The output that should be produced w/ this client program is this; followed by the code.

The output:

The result starts off at 0/1

The product of 9/8 and 2/3 is 3/4

The quotient of 9/8 and 2/3 is 27/16

The sum of 9/8 and 2/3 is 43/24

The difference of 9/8 and 2/3 is 11/24

The two Fractions are not equal

The product of 3/2 and 2/3 is 1/1

client program (don't change)

#include <iostream>
#include "fraction.h"
using namespace std;

int main()
{
    Fraction f1(9,8);
    Fraction f2(2,3);
    Fraction result;

    cout << "The result starts off at ";
    result.print();
    cout << endl;

    cout << "The product of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.multipliedBy(f2);
    result.print();
    cout << endl;

    cout << "The quotient of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.dividedBy(f2);
    result.print();
    cout << endl;

    cout << "The sum of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.addedTo(f2);
    result.print();
    cout << endl;

    cout << "The difference of ";
    f1.print();
    cout << " and ";
    f2.print();
    cout << " is ";
    result = f1.subtract(f2);
    result.print();
    cout << endl;

    if (f1.isEqualTo(f2)){
        cout << "The two Fractions are equal." << endl;
    } else {
        cout << "The two Fractions are not equal." << endl;
    }
    
    const Fraction f3(12, 8);
    const Fraction f4(202, 303);
    result = f3.multipliedBy(f4);
    cout << "The product of ";
    f3.print();
    cout << " and ";
    f4.print();
    cout << " is ";
    result.print();
    cout << endl;
}

This client should produce the output shown here:

The result starts off at 0/1
The product of 9/8 and 2/3 is 3/4
The quotient of 9/8 and 2/3 is 27/16
The sum of 9/8 and 2/3 is 43/24
The difference of 9/8 and 2/3 is 11/24
The two Fractions are not equal.
The product of 3/2 and 2/3 is 1/1

Solutions

Expert Solution

Your answer of first two tasks is as follows (defining constructor)

1. default constructor

Fraction :: Fraction() {
this -> numerator = 0;
this -> denominator = 1;
}

for this , remove the method call void set(arg1,arg2) and add the line below in the class

Fraction() ;

2. Parameterised constructor

Fraction :: Fraction(int numerator , int denominator) {
assert(denominator!=0);
this -> numerator = numerator;
this -> denominator = denominator;
this -> simplify(); // this method reduced any improper fraction

}

or this , remove the method call void set(arg1,arg2) and add the line below in the class

Fraction(int numerator , int denominator) ;

3 . simplify() method to reduce improper fraction

void Fraction :: simplify() {
if(this->numerator == this->denominator) {// check if both are equal , then set 1 to both
this->numerator = this->denominator = 1;
return ;
}
// find greateast common divisor
int min = ((this -> numerator < this -> denominator) ? this -> numerator : this -> denominator);
int gcd =1 ;
for(int i =2;i <= min; i++) {
if (this -> numerator % i == 0 && this -> denominator % i == 0) {
gcd = i;
}
}
this -> numerator = this -> numerator / gcd;
this -> denominator = this -> denominator / gcd;
}

For this method add the below line in the class public section

void simplify();

Mofication in the member function to call this simplify method is as follow

1 . modified addedTo method

Fraction Fraction :: addedTo (Fraction f) {

// previous as it is

// add here to call simplify method
result.simplify();

return result;

}

2. Modified subtact() method

Fraction Fraction :: subtract (Fraction f) {

// previous code
  

// add here to call
result.simplify();

return result;

}

3. modified dividedBy() method

Fraction Fraction :: dividedBy (Fraction f) {

// previous code as it is

// add to call the simply method

result.simplify();
  
return result;
  

}

4 . Modified multipliedBy() method

add const to method declartion too in the class function decleration as follows

Fraction multipliedBy(Fraction F) const;

Fraction Fraction ::multipliedBy (Fraction f) const {

// previous code as it is

// add this to call method
result.simplify();

return result;

}

Image for cross testing


Related Solutions

Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std;...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std; void leapYear(int x); int main() { int x; cout << "Enter a year: "; cin >> x; leapYear (x);   return 0; } void leapYear(int x ) {    if (x % 400 == 0)    {    cout << "This is a leap Year";}    else if    ((x % 4 == 0) && (x % 100 != 0))    {    cout <<...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; //...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; // Structure for storing the process data struct procData { char pname[5]; // Name of a process int arrivt; //Arrival time of a process int pburst; // Burst time of a process int endtime; // Exit time/ Leaving time of a process int remburst; // Remaining burst time of a process int readyFlag; // boolean, Flag for maintaining the process status }; // Global variable...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
code from assignment 1 #include #include using namespace std; const int nameLength = 20; const int...
code from assignment 1 #include #include using namespace std; const int nameLength = 20; const int stateLength = 6; const int cityLength = 20; const int streetLength = 30; int custNomber = -1; // Structure struct Customers { long customerNumber; char name[nameLength]; char state[stateLength]; char city[cityLength]; char streetAddress1[streetLength]; char streetAddress2[streetLength]; char isDeleted = 'N'; char newLine = '\n'; int zipCode; }; int main() { ofstream file; file.open("Customers.dat", fstream::binary | fstream::out); char go; long entries = 0; struct Customers data; do...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
Do an insertion sort based off this code #include <iostream> #define MAX_INT 2147483647 using namespace std;...
Do an insertion sort based off this code #include <iostream> #define MAX_INT 2147483647 using namespace std;    int main(int argc,char **argv) { int* Sequence; int arraySize = 1; // Get the size of the sequence cin >> arraySize; Sequence = new int[arraySize];    // Read the sequence for(int i=0; i<arraySize; i++) cin >> Sequence[i];
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function name: main Purpose:                   main function In parameters: b,r,i Out paramters: trun,error,total,value Version:                   1.0 Author: ********************************************************************************/ void main() {    int i;//declaring this variable to get value for quitting or calaculating series    do {//do while loop to calaculate series until user quits        cout << "Enter 1 to evaluate the series." << endl;       ...
Write a C++ program based on the cpp file below ++++++++++++++++++++++++++++++++++++ #include using namespace std; //...
Write a C++ program based on the cpp file below ++++++++++++++++++++++++++++++++++++ #include using namespace std; // PLEASE PUT YOUR FUNCTIONS BELOW THIS LINE // END OF FUNCTIONS void printArray(int array[], int count) {    cout << endl << "--------------------" << endl;    for(int i=1; i<=count; i++)    {        if(i % 3 == 0)        cout << " " << array[i-1] << endl;        else        cout << " " << array[i-1];    }    cout...
C++ I took 7/20 =( code: #include <iostream> #include<string.h> using namespace std; // function to calculate...
C++ I took 7/20 =( code: #include <iostream> #include<string.h> using namespace std; // function to calculate number non white space characters int GetNumOfNonWSCharacters(string str) { int i = 0; int count = 0; while(str[i] != '\0') { if(str[i] != ' ') { count += 1; } i++; } return count; } // function to calculate numbers of words int GetNumOfWords(string str) { int i = 0; int count = 1; while(str[i] != '\0') { if(str[i] == ' ' && str[i-1]...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT