I'm dividing integers and making it a temporary double so i can get it in a decimal.
To have it with a fraction i just divide the numbers and cout the answer with the mod answer "/" num2. I want to display both the fraction and in decimal, so..

for 10 divided by 3, 3 1/3 is good, but 125 divided by 75 yeilds "1 50/75". How can i get if the simplify the fractions? i.e. " 1 2/3"

Recommended Answers

All 2 Replies

That won't help to reduce/simplify fractions so much as using the Greatest Common Divisor.

Here it is with the Euclidean algorithm, unrolled one iteration.

int GCD( int a, int b )
  {
  while (true)
    {
    a = a % b;
    if (a == 0) return b;

    b = b % a;
    if (b == 0) return a;
    }
  }

So, to simplify a fraction, simply:

void simplify( int& n, int& d )
  {
  int gcd = GCD( n, d );
  n /= gcd;
  d /= gcd;

  // If negative, make it the numerator.
  if (d < 0)
    {
    n = -n;
    d = -d;
    }
  }

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.