一个分数相加的列子,代码如下:
//
// 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;
//
// 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方法的第一行:
请大神指教,为什么报错了,应该怎么写?
我想了下,应该是递归导致了死循环。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。