//

//  Fraction.h

//  FractionTest

//

//  Created by Leven on 15-5-7.

//

#import <Foundation/Foundation.h>

//Fraction类

@interface Fraction : NSObject

@property int numerator, denominator;

-(void) print: (BOOL) b;

-(double) convertToNum;

-(void) setTo: (int) n over: (int) d;

-(Fraction *) reduce;

-(Fraction *) add: (Fraction *) f;

//

//  Fraction.m

//  FractionTest

//

//  Created by Leven on 15-5-7.

//

#import "Fraction.h"

@implementation Fraction

@synthesize numerator, denominator;

-(void) print: (BOOL) b

{

if (b == YES) {

[[self reduce] print: YES];

} else {

NSLog(@"%i/%i", numerator, denominator);

}

}

-(double) convertToNum

{

if (denominator != 0) {

return (double) numerator / denominator;

} else {

return NAN;

}

}

-(void) setTo:(int)n over:(int)d

{

numerator = n;

denominator = d;

}

-(Fraction *) reduce

{

Fraction *result = [Fraction new];

int u = numerator;

int v = denominator;

int temp;

while (v != 0) {

temp = u % v;

u = v;

v = temp;

}

int n = numerator;

int d = denominator;

n /= u;

d /= u;

[result setTo: n over: d];

return result;

}

-(Fraction *) add:(Fraction *)f

{

Fraction *result = [Fraction new];

//相加两个分数

//a/b + c/d = (a * d + b * c) / (b * d)

result.numerator = numerator * f.denominator + denominator * f.numerator;

result.denominator = denominator * f.denominator;

return result;

}

@end

//

//  main.m

//  FractionTest

//

//  Created by Leven on 15-5-7.

//

#import <Foundation/Foundation.h>

#import "Fraction.h"

int main(int argc, const char * argv[]) {

@autoreleasepool {

Fraction *aFraction = [[Fraction alloc] init];

Fraction *bFraction = [[Fraction alloc] init];

Fraction *resultFraction;

[aFraction setTo: 1 over: 4];

[bFraction setTo: 1 over: 2];

//打印结果

[aFraction print: NO];

NSLog(@"+");

[bFraction print: NO];

NSLog(@"=");

resultFraction= [aFraction add: bFraction];

[resultFraction print: YES];

[resultFraction print: NO];

}

return 0;

}

main测试的时候报错了，在reduce方法的第一行：

0