|
Salt Lake City Thursday, 2013.05.23 01:25 MDT [GMT-7] |
![]() |
Condition: Mostly Clear Temperature: 8°C/46°F Barometer: 1012.5 mb and rising |
| IT | |
|---|---|
| MIX | |
| News |
/**
* @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;
}
Vincenzo Maggio