Calculating negative fractions in Objective C

Posted by Mark Reid on Stack Overflow See other posts from Stack Overflow or by Mark Reid
Published on 2010-03-20T23:06:14Z Indexed on 2010/03/20 23:11 UTC
Read the original article Hit count: 375

I've been coding my way through Steve Kochan's Programming in Objective-C 2.0 book. I'm up to an exercise in chapter 7, ex 4, in case anyone has the book.

The question posed by the exercise it will the Fraction class written work with negative fractions such as -1/2 + -2/3?

Here's the implementation code in question -

@implementation Fraction

@synthesize numerator, denominator;

-(void) print
{
NSLog(@"%i/%i", numerator, denominator);
}

-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}

-(double) convertToNum
{
if (denominator != 0)
    return (double) numerator / denominator;
else
    return 1.0;
}

-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a * d) + (b * c)) / (b * d)

// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;

resultNum = (numerator * f.denominator) + (denominator * f.numerator);
resultDenom = denominator * f.denominator;

[result setTo: resultNum over: resultDenom];
[result reduce];

return result;
}

-(Fraction *) subtract: (Fraction *) f
{
// To subtract two fractions:
// a/b - c/d = ((a * d) - (b * c)) / (b * d)

// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;

resultNum = numerator * f.denominator - denominator * f.numerator;
resultDenom = denominator * f.denominator;

[result setTo: resultNum over: resultDenom];
[result reduce];

return result;
}

-(Fraction *) multiply: (Fraction *) f
{
// To multiply two fractions
// a/b * c/d = (a*c) / (b*d)

// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;

resultNum = numerator * f.numerator;
resultDenom = denominator * f.denominator;

[result setTo: resultNum over: resultDenom];
[result reduce];

return result;
}

-(Fraction *) divide: (Fraction *) f
{
// To divide two fractions
// a/b / c/d = (a*d) / (b*c)

// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;

resultNum = numerator * f.denominator;
resultDenom = denominator * f.numerator;

[result setTo: resultNum over: resultDenom];
[result reduce];

return result;
}

-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;

while (v != 0) {
    temp = u % v;
    u = v;
    v = temp;
}

numerator /= u;
denominator /= u;
}

@end

My question to you is will it work with negative fractions and can you explain how you know? Part of the issue is I don't know how to calculate negative fractions myself so I'm not too sure how to know.

Many thanks.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about math