tags:

views:

120

answers:

3
-(void) addFractions: (Fraction*) f
{
    numerator = numerator * f.denominator
    + denominator *f.numerator;

    denominator = denominator *f.denominator;
}

//This is objective c-2.0

// this is the .h file for the .m above

-(void) addFractions : (Fraction*) f;

Don’t forget that you can refer to the Fraction that is the receiver of the message by its fields:numerator and denominator.On the other hand,you can’t directly refer to the instance variables of the argument fthat way.Instead,you have to obtain them by apply- ing the dot operator to f(or by sending an appropriate message to f)

+2  A: 

In order to bring both fractions to use the same denominator.

I mean, a/b+c/d = a*d/(b*d) + c*b/(d*b) = (a*d + c*b) / (b*d).

Ofir
A: 

a.b (a dot b) is syntactic sugar for using the member variable accessors [a b], or mutators [a setb] when used as an lvalue.

I really don't understand what you are complaining about; this code is as clear And compact as any language is possible to be. That's how I would write it in pseudocode, too.

The rest is just maths.

Alex Brown
In Obj-C the getter is usually just the property name, i.e., `[a b]`.
Stephen Darlington
thanks, that's true. I have updated the code.
Alex Brown
@Alex: The setter by default is `[a setB:...]`, not `[a setb]`.
KennyTM
I'm not confused about the math part,I understand to add fractions.What I don't understand is wy the member variables have to be accessed using this notation " f.numerator and f.denominator" instead of accessing them directly.
lampShade
+1  A: 

Imagine you have two fractions p/q and r/s that you'd like to add to a new fraction a/b. What does each line do?

// a = (p * s) + (q * r)
numerator = numerator * f.denominator + denominator * f.numerator;

// b = (r * s)
denominator = denominator *f.denominator;

Together you have:

 a    p * s + q * r
--- = -------------
 b        r * s

This is the traditional way to add two fractions with arbitrary, different denominators. Here's an example -- say you wanted to add 3/5 and 2/9:

 a    3 * 9 + 2 * 5   27 + 10   37
--- = ------------- = ------- = --
 b        5 * 9          45     45

Verifying, we see that this is indeed correct.

John Feminella