Menu

Friday, 28 November 2014

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

//Engr. Ahmad Furqan Attari
//Chapter 6, Problem 11
#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;
class fraction
{
private:
 int num, den;
public:
 fraction()
 {}
 fraction(int n, int d):num(n), den(d)
 {
 }
 void take_frac(void)
 {
  char ch;
  cin >> num >> ch >> den;
 }
 void show_frac(void)
 {
  cout << num << "/" << 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)
{
 fraction a, b, c,d,e,f;
 char ch;
 do
 {
  cout << "Enter fraction a: ";
  a.take_frac();
  cout << "Enter fraction b: ";
  b.take_frac();
  c.add_frac(a, b);
  a.show_frac();
  cout << " + ";
  b.show_frac();
  cout << " = ";
  c.show_frac();
  cout << endl;
  d.sub_frac(a, b);
  a.show_frac();
  cout << " - ";
  b.show_frac();
  cout << " = ";
  d.show_frac();
  cout << endl;
  e.mul_frac(a, b);
  a.show_frac();
  cout << " * ";
  b.show_frac();
  cout << " = ";
  e.show_frac();
  cout << endl;
  f.div_frac(a, b);
  a.show_frac();
  cout << " % ";
  b.show_frac();
  cout << " = ";
  f.show_frac();
  cout << endl << "Enter again? (y/n): ";
  ch = _getche();
  cout << endl;
 } while (ch != 'n');
}

No comments:

Post a Comment