ReduceFraction and CommonDenominator Help

Hey i have no clue what to put in the ReduceFration and CommonDemoninator sections.

I know that you call the gcd function for ReduceFration and lcm function for CommonDenominator.

Should be easy few lines of code but I'm a Beginner!

Here's the code:

#include <iostream>
using namespace std;
 
int gcd(int x,int y)
{
	int t;
	t = x % y;
    while (t != 0)
    {
        x = y;
        y = t;
        t = x % y;
    }
        return y;
}

int lcm(int x,int y)
{
	int ans, cnt;

	if (x > y)
	{
		cnt = x;
	}
	else
	{
		cnt = y;
	}
	ans = 0;
	while (ans == 0)
	{
		if (cnt % x == 0 && cnt % y == 0)
		{
			ans = cnt;
		}
		else
		{
			cnt++;
		}	
	}
	return ans;
}

void ReduceFraction(int &num,int &den)
{
   // Missing function goes here!
}
void CommonDenominator(int &num1, int &den1, int &num2, int &den2)
{
   // Missing function goes here!
}

void main()
{
	int num1, den1, num2, den2, newnum, newden;
	char slash1, slash2, op;

	cout << "\nFraction Calculator\n\n";
	cout << "Add, subtract, multiply & divide - positive fractions only\n";
	cout << "Enter '0/0 + 0/0' to quit.\n";

	// Input will be assumed to be in correct form for simplification
	// Input data before loop in case they want to exit right away

	cout << "\n> ";
	cin >> num1 >> slash1 >> den1 >> op >> num2 >> slash2 >> den2;
	while (num1 + den1 + num2 + den2 > 0)
	{
		// Reduce both fractions to keep integers as small as possible
		ReduceFraction(num1, den1);
		ReduceFraction(num2, den2);
		switch (op) 
		{
			case '+':
			   // Find common denominator and add
			   CommonDenominator(num1,den1,num2,den2);
			   newnum = num1 + num2;
			   newden = den1;
			   break;
			case '-':
			   // Find common denominator and subtract
			   CommonDenominator(num1,den1,num2,den2);
			   newnum = num1 - num2;
			   newden = den1;
			   break;
			case '*':
			   // Multiply numerators and multiply denominators
			   newnum = num1 * num2;
			   newden = den1 * den2;
			   break;
			case '/':
			   // Invert and multiply
			   newnum = num1 * den2;
			   newden = den1 * num2;
		}
		// Reduce the answer to lowest terms
		ReduceFraction(newnum, newden);

		// Output the results
		cout << num1 << "/" << den1 << " " << op << " ";
		cout << num2 << "/" << den2 << " = ";
		cout << newnum << "/" << newden << endl;

		// Input data for next iteration of loop
		cout << "\n> ";
		cin >> num1 >> slash1 >> den1 >> op >> num2 >> slash2 >> den2;
	}
}
Just do what you usually do in math:
To reduce fraction you should divide both bumerator and denomunator by their greatest common divisor
1
2
3
4
5
6
void ReduceFraction(int &num,int &den)
{
    int d = gcd(num, den);
    num /= d;
    den /= d;
}

Do common denominator yourself
Last edited on
I'm not very good at math, for I haven't taken a course since high school so that's my problem lol

Thanks for the ReduceFraction example!
Topic archived. No new replies allowed.