Math function not showing correct results
I need some help getting correct results on开发者_开发问答 fraction results. After adding them together and reducing, they should show a final result of 3/4, but I'm getting a result of 3/1. Can you show me where my functions are wrong?
Fraction.h
#import <Foundation/Foundation.h>
//The fraction class
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(void) setTo:(int)n over:(int)d;
-(double) convertToNum;
-(void) add: (Fraction *) f;
-(void) reduce;
@end
Fraction.m
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print{
NSLog(@"%i/%i", numerator, denominator);
}
-(double) convertToNum{
if (denominator != 0)
return (double) numerator/denominator;
else
return 1.0;
}
-(void) setTo:(int)n over:(int)d{
numerator = n;
denominator = d;
}
//add a fraction to the receiver
-(void) add: (Fraction *) f {
//To add two fractions
//a/b + c/d = ((a*d) + (b*c))/(b * d)
numerator = (numerator * [f denominator])
+ (denominator * [f numerator]);
denominator = [f denominator];
[self reduce];
}
-(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
FractionTest.m
#import <Foundation/Foundation.h>
#import "Fraction.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc]init];
Fraction *bFraction = [[Fraction alloc]init];
//Set two fractions to 1/4 and 1/2 and add them together
[aFraction setTo:1 over:4];
[bFraction setTo:1 over:2];
//Print the results
[aFraction print];
NSLog(@"+");
[bFraction print];
NSLog(@"=");
[aFraction add:bFraction];
//reduce the result of the addition and print the result
[aFraction reduce];
[aFraction print];
[aFraction release];
[bFraction release];
[pool drain];
return 0;
}
Can you tell what I'm doing wrong? TIA
Check your math :-)
-(void) add: (Fraction *) f {
//To add two fractions
//a/b + c/d = ((a*d) + (b*c))/(b * d)
numerator = (numerator * [f denominator])
+ (denominator * [f numerator]);
denominator = [f denominator];
You are setting the object's denominator to the argument's denominator, when you should be setting it to the result of the multiplication of the two.
denominator = denominator * [f denominator];
精彩评论