Review a classmates method descriptions and use C to define

Review a classmate\'s method descriptions and use C++ to define one method from each of the two classmates\' listings.

// Add two fractions and store the sum in reduced form.

Int int add(int, int)

Will add the the two fractions and maybe call the reduce function to then reduce the result

How can I define the example method above using C++. I wouldn\'t preferably use this method myself, but alas, my assignment is to take this method and define it.

Solution

Please follow the code and comments for description :

CODE :

#include <iostream>

using namespace std;

class FractionCalc // class to run the code
{
public:
   FractionCalc(int n = 0, int d = 1); // required initialisations
   void add(FractionCalc fract1, FractionCalc fract2);
   void printResult();
private:
   void reduce();
   int num, den;
};

FractionCalc::FractionCalc(int n, int d) { // constructor model
   num = n;
   if (d <= 0)   {
       cout << \"Sorry, The denominator is equal Invalid.!!!\" << endl;
       exit(0);
   } else {
       den = d;
   }
  
}

int gcd(int a, int b) { // get the gcd value to reduce the data
   if(b == 0) {
       return a;
   } else {
       return gcd(b, a%b); // return the gcd value recursively
   }
  
}

void FractionCalc::reduce() { // get the GCD and divide num and den by it to reduce
   int divisor = gcd(num, den); // get the gcd value
   num /= divisor; // save the datt ot the local variables
   den /= divisor;
}

void FractionCalc::add(FractionCalc fract1, FractionCalc fract2) { //function to add the values
   num = (fract1.num * fract2.den) + (fract2.num * fract1.den); // get the respective values
   den = fract1.den * fract2.den;
   reduce(); //reduce the data
}

void FractionCalc::printResult() { // method to print the data that has been generated
   cout << \"The Reduced Resultant FractionCalc form of the data is : \" << num << \"/\" << den << endl;
}

int main() { // driver method
   FractionCalc x(8,3), y(5,6), z; // local varaibles
   z.add(x,y); // pass the data to the functions
   z.printResult(); // call the function to print the data
   return 0;
}


OUTPUT :

The Reduced Resultant FractionCalc form of the data is : 7/2


Hope this is helpful.

Review a classmate\'s method descriptions and use C++ to define one method from each of the two classmates\' listings. // Add two fractions and store the sum in
Review a classmate\'s method descriptions and use C++ to define one method from each of the two classmates\' listings. // Add two fractions and store the sum in

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site