home Sandy, UT
Wednesday, 2017.11.22
04:02 MDT [GMT-7]
Brionews - Company Logo Condition: Clear
Temperature: 4.1°C (39.4°F)
Barometer: 1030 mb and rising
IT
MIX
News
Low Cost Affordable C C++ PHP mySQL Perl Programs Development
Assignment for C++ class.
Assignment was to write a tiny calculator for the sum of 2 fractions.
All the class chose to input the 2 numerators and the 2 denominators; I wrote a tiny parser.
Rather easy and I had some fun too.
Input the fractions in the form: num/den, like: 25/7 or 8/25, no spaces
Download the executable: fraction.exe
June 14, 2004

Sum of 2 Fractions

/**
  *  @title: fraction.cpp
  *  @date: 2004.06.14
  *  @author: vinnie */

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

#ifdef __BORLANDC__
  #pragma argsused
#endif

using namespace std;

struct Frac
{ int fNum;
  int fDen;
  };

// `.`.`.`.`.

/** passed a string fraction, returns int numerator */
int num( char *str)
{ char tmpStr[12];
  memset( tmpStr, 0, 12);
  for ( short i = 0; *str != 0x2f; i++, str++)
    tmpStr[i] = *str;
  return atoi(tmpStr);
  }

/** passed a string fraction, returns int denominator */
int den( char *str)
{ char tmpStr[12];
  memset( tmpStr, 0, 12);
  while ( *str != 0x2f) str++;
  str++;
  for ( short i = 0; *str != '\0'; i++, str++)
    tmpStr[i] = *str;
  return atoi(tmpStr);
  }

/** passed 2 int, returns the Greatest Common Divisor */
int gcd( int a, int b)
{ int c = 0;
  while ( b != 0)
  { c = a % b;
    a = b;
    b = c;
    }
  return a;
  }

/** passed a fraction, tries to simplify it */
void simplify( Frac *pFrac)
{ int g = gcd( pFrac->fNum, pFrac->fDen);
  if ( g >= 1)
     { pFrac->fNum /= g;
       pFrac->fDen /= g;
       }
  }

// `.`.`.`.`.

void main( )
{
  /** allocates 2 strings and sets them to zero */
  char lpzFrac0[22], lpzFrac1[22];
  memset(lpzFrac0, 0, 22);
  memset(lpzFrac1, 0, 22);

  /** asks and accepts 2 fractions */
  cout << "Sum of 2 fractions.\nEnter first fraction here: ";
  cin >> lpzFrac0;
  cout << "Enter 2nd fraction here: ";
  cin >> lpzFrac1;

  /** splits the fractions into numerators and denominators */
  int numF0, denF0, numF1, denF1;
  numF0 = num( lpzFrac0);
  denF0 = den( lpzFrac0);
  numF1 = num( lpzFrac1);
  denF1 = den( lpzFrac1);

  /** gets the greatest common divisor */
  int iGcd = gcd(denF0, denF1);
  /** gets the least common multiple */
  int iLcm = (denF0 * denF1) / iGcd;
  /** gets the sum of the numerators */
  int iSum = numF0 * iLcm/denF0 + numF1 * iLcm/denF1;

  Frac fraction, *pFrac = &fraction;
  fraction.fNum = iSum;
  fraction.fDen = iLcm;
  simplify( pFrac);

  cout << "Sum of: " << lpzFrac0 << " + " << lpzFrac1 << " = " << iSum \
       << "/" << iLcm << " = " << pFrac->fNum << "/" << pFrac->fDen \
       << '\n' << "done!" << '\n' ;
//  return 0;
}

2004.06.14

Vincenzo Maggio