数学函数未显示正确的结果

时间:2011-03-17 23:11:22

标签: objective-c c

我需要一些帮助才能在分数结果上获得正确的结果。将它们加在一起并减少后,它们应该显示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

1 个答案:

答案 0 :(得分: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];