标签:
方法为:a/b+c/d=( (a*d)+(b*c) )/(b*d)
(1).h文件
#import <Foundation/Foundation.h>
@interface Fraction : NSObject //fraction分数
@property int numerator,denominator;//denominator分母 numerator分子
-(void)print;
-(void)setTo:(int)n over :(int)d;
-(double) convertToNum; //convertion转换
-(void)add:(Fraction *)f;
-(void)reduce; //reduce减少
@end
(2).m文件
#import"Fraction.h"
@implementationFraction
@synthesizenumerator,denominator;
-(void)print
{
NSLog(@"%i/%i",numerator,denominator);
}
-(double)convertToNum
{
if(denominator!=0)
{
return(double)numerator/denominator;
}
else
returnNAN;
}
-(void)setTo:(int)n over:(int)d
{
numerator=n;
denominator=d;
}
//添加Fraction到消息接受
-(void)add:(Fraction*)f
{
//添加两个分数:
//a/b+c/d=((a*d)+(b*c))/(b*d) //两个分数相加的另一种求法
numerator=numerator* f.denominator+denominator* f.numerator; //这里的*是乘的意思
denominator=denominator* f.denominator;
}
-(void)reduce
{
intu=numerator;
intv=denominator;
inttemp;
while(v!=0) {
temp=u%v;
u=v; //求最大公约数的方法
v=temp;
}
numerator/=u; 这两步是化简分数
denominator/=u;
}
@end
标签:
原文地址:http://www.cnblogs.com/iQingYang/p/5245543.html