# subtracting fractions in classes

• 03-18-2009
rushhour
subtracting fractions in classes
Hi

I am having difficulty in creating a function for subtracting fractions in a class. I was given this advice to do it

Quote:

Note:subtraction can be achieved by adding (by changing the sign of the numerator - this can be achieved by multiplying it by -1).
and my attempt is shown below:

Code:

```void Fraction::subtract(Fraction f2, Fraction& f3) {   int s_denom = denom * f2.denom ;   int s_num = ((num * -1) * f2.denom) - ((f2.num * -1) * denom);   f3.create(s_num,s_denom);   f3.simplify(); }```
but a subtraction seems to come out a little wrong for example the output is:
Code:

```Enter first numerator: 3 Enter first denominator: 4 Enter second numerator: 2 Enter second denominator: 4 3/4 - 2/4 = -1/4```
Can anyone help me to correct this little error.
Thanks if you can.
• 03-18-2009
R.Stiltskin
Code:

```void Fraction::subtract(Fraction f2, Fraction& f3) {   int s_denom = denom * f2.denom ;   int s_num = num * f2.denom - f2.num  * denom;   f3.create(s_num,s_denom);   f3.simplify(); }```
Multiply f2.num by -1 and add the products, or don't bother multiplying by -1 and subtract the second product from the first. Either way, you shouldn't multiply num by -1.