You're making the math over-complicated, and apt to return non-integer numerators and denominators.
For example, adding two fractions:
1 2
|
n1 + n2 = (n1 *d2 + n2 * d1)
d1 d2 d1 * d2
|
can be generically expressed this way:
1 2
|
int NewNum = num1 * denom2 + num2 * denom1;
int NewDenom = denom1 * denom2;
|
Your usage should be something along the lines of :
num * frac2.denom. . . etc.
Subtraction is the same concept, just changing sign from + to -.
However, if you make your parameterized constructor this way:
1 2 3 4 5 6
|
fraction::fraction(int x, int y)
{
num = x;
denom = y;
reduce();
}
|
and then in your math calculations do:
1 2 3
|
fraction fraction::add(fraction& frac2)
fraction answer (num * frac2.denom + denom * frac2.num, denom * frac2.denom)
// same idea for all four math functions
|
you won't have to call reduce() - it will run whenever you create a fraction object.
reduce() should account for negative numerator and/or denominator:
1 2 3 4 5 6 7 8 9 10
|
void fraction::reduce()
{
// right here you should include a plus/minus determination
//remember it and apply after gcd(. . .)
int answer = gcd(num, denom);
//factor = denom / num;
num /= answer;
denom /= answer;
}
|
output() should account for improper fractions (num> denom)
1 2 3 4 5
|
void fraction::output()
{
if(num > denom) cout << num/denom << " ";
cout << num % denom << "/" << denom;
}
|
dhayden20:
Did you fix the bug in gcd()? A previous version assumed that x>y. |
Actually, since x and y are reversed each iteration of reduce, it is only necesary to ensure that both are positive integers.