subtracting fractions in classes

This is a discussion on subtracting fractions in classes within the C++ Programming forums, part of the General Programming Boards category; Hi I am having difficulty in creating a function for subtracting fractions in a class. I was given this advice ...

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    42

    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

    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.

  2. #2
    Registered User
    Join Date
    Feb 2003
    Posts
    595
    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.
    Last edited by R.Stiltskin; 03-18-2009 at 08:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 11:47 AM
  2. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-24-2004, 12:22 AM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 08:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 04:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21