Menu

Friday, 28 November 2014

Chapter 6,Problem 12:Object Oriented Programming by Robert Lafore in C++ Solution Manual

//Engr. Ahmad Furqan Attari
//Chapter 6, Problem 11
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <cmath>
using namespace std;
class fraction
{
private:
     int num, den;
public:
     fraction()
     {}
     fraction(int n, int d) :num(n), den(d)
     {
           lowterms();
     }
     void take_frac(void)
     {
          char ch;
          cin >> num >> ch >> den;
     }
     void show_frac(void)
     {
          cout << setw(2)<<num << "/" <<setw(2)<< den;
     }
     void lowterms(void) // change ourself to lowest terms
     {
          long tnum, tden, temp, gcd;
          tnum = labs(num); // use non-negative copies
          tden = labs(den); // (needs cmath)
          if (tden == 0) // check for n/0
          {
               cout << "Illegal fraction : division by 0"; exit(1);
          }
          else if (tnum == 0) // check for 0/n
          {
               num = 0; den = 1; return;
          }
          // this ‘while’ loop finds the gcd of tnum and tden
          while (tnum != 0)
          {
               if (tnum < tden) // ensure numerator larger
               {
                    temp = tnum; tnum = tden; tden = temp;
               } // swap them
               tnum = tnum - tden; // subtract them
          }
          gcd = tden; // this is greatest common divisor
          num = num / gcd; // divide both num and den by gcd
          den = den / gcd; // to reduce frac to lowest terms
         }
     void add_frac(fraction a, fraction b)
     {
          num = a.num*b.den + a.den*b.num;
          den = a.den*b.den;
          lowterms();
     }
     void sub_frac(fraction a, fraction b)
     {
          num = a.num*b.den - a.den*b.num;
          den = a.den*b.den;
          lowterms();
     }
     void mul_frac(fraction a, fraction b)
     {
          num = a.num*b.num;
          den = a.den*b.den;
          lowterms();
     }
     void div_frac(fraction a, fraction b)
     {
          num = a.num*b.den;
          den = a.den*b.num;
          lowterms();
     }
};
void main(void)
{
     int den;
     fraction f[9],res;
     do
     {
          cout << "Enter a denominator(<10): ";
          cin >> den;
     } while (den > 9);
     cout << "          ";
     for (int i = 0; i < den-1; i++)
     {
          f[i] = { i + 1, den };
          f[i].show_frac();
          cout << "    ";
     }
     for (int i = 0; i < den - 1; i++)
     {
          cout << endl;
          f[i].show_frac();
          cout << "     ";
          for (int j = 0; j < den - 1; j++)
          {
               res.mul_frac(f[i], f[j]);
               res.show_frac();
               cout << "    ";
          }
     }
     _getch();
}

No comments:

Post a Comment