2011-03-17 74 views
1

我需要一些幫助才能在分數結果中獲得正確的結果。在將它們加在一起並減少後,它們應該顯示3/4的最終結果,但是我得到3/1的結果。你能告訴我我的功能在哪裏嗎?數學函數不能顯示正確的結果

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; 
} 

你能告訴我在做什麼錯? TIA

回答

0

檢查你的數學:-)

-(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]; 

您是對象的分母設定參數的分母,當你需要將其設置爲兩個相乘的結果。

denominator = denominator * [f denominator];