两个分数的加减乘除
第一步: 先定义一个分数的类
#import "Fraction.h"
@implementation Fraction
//初始化
- (id)initWithFenzi:(NSInteger)fenzi withFenmu:(NSInteger)fenmu{
self = [super init];
if (self) {
_fenzi = fenzi;
_fenmu = fenmu;
}
return self;
}
//便利构造器
+ (id)fractionWithFenzi:(NSInteger)fenzi withFenmu:(NSInteger)fenmu{
Fraction *num = [[Fraction alloc]initWithFenzi:fenzi withFenmu:fenmu];
return num;
}
第二步:对分子分母进行约分//最大公约数
- (NSInteger)greatestCommonDivisorWithOneNum:(NSInteger)oneNum andAnotherNumber:(NSInteger)anotherNum{
while (anotherNum != 0) {
NSInteger temp = oneNum % anotherNum;
oneNum = anotherNum;
anotherNum = temp;
}
return oneNum;
}
//约分
- (void)reductionOfFraction{
NSInteger temp = [self greatestCommonDivisorWithOneNum:_fenzi andAnotherNumber:_fenmu];<span style="color:#990000;">//self指代的是调用这个函数的分数,也就是谁
调用这个函数,self指代的就是谁</span>
_fenzi = _fenzi / temp;
_fenmu = _fenmu / temp;
}
第三步:进行加减乘除
传入两个分数类型的数,先进行约分,变成最简分数再进行加减乘除,再约分
或者先对两个分数进行加减乘除,再对最后的结果进行约分
加减乘除注意的是:加减法要先通分,乘法直接分子与分子相乘,分母与分母相乘,除法是被除数的分子与除数的分母相乘,被除数的分母与除数的分子相乘
+ (Fraction *)addWithAFraction:(Fraction *)aFraction withBFraction:(Fraction *)bFraction{
Fraction *add = [[Fraction alloc]init];
add.fenzi = aFraction.fenzi * bFraction.fenmu + aFraction.fenmu * bFraction.fenzi;
add.fenmu = aFraction.fenmu * bFraction.fenmu;
[add reductionOfFraction];
return add;
}
+ (Fraction *)subWithAFraction:(Fraction *)aFraction withBFraction:(Fraction *)bFraction{
Fraction *sub = [[Fraction alloc]init];
sub.fenzi = aFraction.fenzi * bFraction.fenmu - aFraction.fenmu * bFraction.fenzi;
sub.fenmu = aFraction.fenmu * bFraction.fenmu;
[sub reductionOfFraction];
return sub;
}
+ (Fraction *)multWithAFraction:(Fraction *)aFraction withBFraction:(Fraction *)bFraction{
Fraction *mult = [[Fraction alloc]init];
mult.fenzi = aFraction.fenzi * bFraction.fenzi;
mult.fenmu = aFraction.fenmu * bFraction.fenmu;
[mult reductionOfFraction];
return mult;
}
+ (Fraction *)devidWithAFraction:(Fraction *)aFraction withBFraction:(Fraction *)bFraction{
Fraction *devid = [[Fraction alloc]init];
devid.fenzi = aFraction.fenzi * bFraction.fenmu;
devid.fenmu = aFraction.fenmu * bFraction.fenzi;
[devid reductionOfFraction];
return devid;
}
第四步:输出函数
- (void)print{
NSLog(@"约分后的分数是%ld/%ld", _fenzi, _fenmu);
}