// FengShu.m
#import "FengShu.h"
@implementation FengShu
@synthesize a;
-(void)setB:(NSInteger)_b //设置器
{
if(_b==0)
{
_b=1;
}
else{
b=_b;
}
}
-(NSInteger)b{ //访问器
return b;
}
-(id)initWithA:(int)_a B:(int)_b
{
if(self==[super init])
{
self.a=_a;
self.b=_b; //[self setB:_b];
}
return self;
}
-(void)add:(FengShu *)aFraction
{
self.a=self.a*aFraction.b+self.b*aFraction.a;
self.b=self.b*aFraction.b;
[self reduce];
}
-(void)subtract:(FengShu *)aFraction
{
self.a=self.a*aFraction.b-self.b*aFraction.a;
self.b=self.b*aFraction.b;
[self reduce];
}
//分数约分
- (void)reduce
{
int aa=abs(self.a);
int bb=abs(self.b);
//int min =(self.a<self.b)?self.a:self.b;
int min =(aa<bb)?aa:bb;
int s =1;//公约数
for(int i=1;i<=min;i++)
{
if(self.a%i==0&&self.b%i==0)
{
s=i;
}
}
self.a /=s;
self.b /=s;
}
-(void)print{
NSLog(@"a=%d/b=%d",self.a,self.b);}
@end
// FengShu.h
#import <Foundation/Foundation.h>
@interface FengShu : NSObject
{
NSInteger a;//分子
NSInteger b;//分母
}
@property(nonatomic,assign) NSInteger a;
@property(nonatomic,assign) NSInteger b;
-(id)initWithA:(NSInteger)_a B:(NSInteger)_b;
-(void)add:(FengShu *)aFraction;
-(void)subtract:(FengShu *)aFraction;
-(void)reduce;
-(void)print;
@end