开发者社区> 问答> 正文

iOS 练习题报错:EXC_BAD_ACCESS?报错

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


//

//  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方法的第一行:

请大神指教,为什么报错了,应该怎么写?



展开
收起
爱吃鱼的程序员 2020-06-14 16:08:58 461 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    我想了下,应该是递归导致了死循环。

    2020-06-14 16:09:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载