Recently I had this nack to make a program that does fraction operations like adding, subtracting, etc. But I can't seem to figure out how to reduce a fraction into it's simplest form. What codes should I use to reduce the fractions into simplest form?
you can probably use modulo to detect the GCF you'd most likely have to convert it to a string for output or it would show up as decimal. Maybe something like.
float firstFraction = 1/2; // arbitrary value assign a fraction you want.
float secondFraction = 3/16 ;// assign another fraction.
// convert decimal to whole number to get numerator of result
int numerator = (firstFraction + secondFraction) * 100;
int denominator = 100;
// start from value of numerator and move down to 1.
// starting from the highest possible divisor would be faster to get to
// the Greatest Common Factor
for(int divisor = numerator; divisor > 0; divisor--)
{
// found the GCF
if(numerator % divisor == 0 && denominator % divisor == 0)
{
// simplify numerator and denominator
numerator /= divisor;
denominator /= divisor;
break;
}
}
cout << numerator << "/" << denominator;
something like that probably. It would be better if you make a class for it though. Then overload the arithmetic operators.