Why do the instance variables of the object being passed in have to be accessed using the dot notation?
-(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开发者_StackOverflow中文版 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)
In order to bring both fractions to use the same denominator.
I mean, a/b+c/d = ad/(bd) + cb/(db) = (ad + cb) / (b*d).
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.
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.
精彩评论