Saturday, May 22, 2010

C++ question!?

Would like to ask what formulas or methods are there for me to simplify fractions to reduced forms (for eg 25/50 -%26gt; 1/2) using C++ program

C++ question!?
you could normally divide the fraction you want to be simplified. that is for example, divide 25 by 50 and you get 0.5 using double type.





then do this 0.5/1





the 1 in the denominator is not a fraction actually. its some sort of trick to get your simplified form (i made it up :-) but it should work)





now multiply the numerator until you get a value of the closest integer. get the number you needed to get closest integer in the numerator and multiply that with the denominator.





in this example 0.5 in the numerator. you need to get a closest integer here so you multiply by 2.





0.5*2 = 1 (1 is the closest integer)


get the number 2 (number needed to get the closest integer) and multiply with the denominator and you get a 2 (1*2 = 2);





another example (6 divided by 9)


you get .666 with normal division assuming you use double type.





now multiply this .666 by a number to get a closest integer.


multiply that number to the denominator to get your real denominator.





.666*1 = .666 not the closest integer


.666*2 = 1.23 not quite as well


.666*3 = 1.99 its good enough if you round off to 2


closest integer is 2 (.666*3)





numerator is 2





to get denominator multiply 3 with the 1 in denominator.


you get 1*3 = 3;





and you get 2/3;





good luck
Reply:To do this, let us define a small simple C++ class CFraction:


==================================


#include %26lt;iostream%26gt;%26gt;


using namespace std;





class CFraction


{


public:


int iNumerator;


int iDenominator;


double dValue;





//constructor...


CFraction( int iNumeratorParam, int iDenominatorParam )


{


iNumerator = iNumeratorParam;


iDenominator = iDenominatorParam;


dValue = iNumerator/ iDenominator;


}





//Reduce (what you wanted in your question):


CFraction reduce()


{


int iGCD = getGCD();


CFraction retVal( iNumerator/iGCD, iDenominator/iGCD );


return retVal;


}





//Display fraction value


void display()


{


cout %26lt;%26lt; iNumerator %26lt;%26lt; "/" %26lt;%26lt; iDenominator;


}





private:


//private method to get GCD


int getGCD( int iNum1, int iNum2 )


{


int remainder = num2 % num1;


if ( remainder != 0 )


return gcd( remainder,num1 );


return num1;


}


}


==================================





And here is how you use it, say you want to reduce 25/50:





==================================





int main()


{


CFraction fracOriginal( 25, 50 );


CFraction fracReduced = fracOriginal.reduce();





cout %26lt;%26lt; "Reduced fraction is:" %26lt;%26lt; endl;


fracReduced.display();


return 0;


}





=====================================


DISCLAIMER: I just typed it up, may contain typos


No comments:

Post a Comment