iOS 练习题报错:EXC_BAD_ACCESS

紫川云 发布于 2015/05/08 00:17
阅读 496
收藏 0

【Gopher China万字分享】华为云的Go语言云原生实战经验!>>>

一个分数相加的列子,代码如下:


//

//  Fraction.h

//  FractionTest

//

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

//  Copyright (c) 2015年 Leven. All rights reserved.

//


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

@end



//

//  Fraction.m

//  FractionTest

//

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

//  Copyright (c) 2015年 Leven. All rights reserved.

//


#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.

//  Copyright (c) 2015年 Leven. All rights reserved.

//


#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
紫川云
紫川云
我想了下,应该是递归导致了死循环。
返回顶部
顶部