本文主要是介绍求两个分数的加减乘除,并比较大小,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//初始化分子分母
-(instancetype)initWithFz:(NSInteger)fz andFm:(NSInteger)fm{if (self = [super init]) {_fz = fz;_fm = fm;}return self;}//便利构造器
+(instancetype)initWithFz:(NSInteger)fz andFm:(NSInteger)fm{Fraction * f = [[Fraction alloc]initWithFz:fz andFm:fm];return f;
}//最大公约数
-(NSInteger)maxDivisor:(NSInteger)num1 : (NSInteger)num2{if (num1 * num2 == 0) {return 0;}else{NSInteger max = (num1>num2) ? num1 : num2;NSInteger min = (num1<num2) ? num1 : num2;NSInteger rem = 1;while (rem != 0) {rem = max % min;max = min;min = rem;}return max;}
}//约分
-(void)reduceFraction{NSInteger greatCommonDivisor = [self maxDivisor:_fz :_fm];if (greatCommonDivisor == 0) {return;}else{_fz/=greatCommonDivisor;_fm/=greatCommonDivisor;}
}//相加
-(Fraction *)addFraction:(Fraction *)frac{Fraction * f = [[Fraction alloc]init];f.fz = _fz * frac.fm + _fm * frac.fz;f.fm = _fm * frac.fm;[f reduceFraction];return f;
}//相减
-(Fraction *)subFraction:(Fraction *)frac{Fraction * f = [[Fraction alloc]init];f.fz = _fz * frac.fm - _fm * frac.fz;f.fm = _fm * frac.fm;[f reduceFraction];return f;
}//相乘
-(Fraction *)mulFraction:(Fraction *)frac{Fraction * f = [[Fraction alloc]init];f.fz = _fz * frac.fz;f.fm = _fm * frac.fm;[f reduceFraction];return f;
}//相除
-(Fraction *)divFraction:(Fraction *)frac{Fraction * f = [[Fraction alloc]init];f.fz = _fz * frac.fm;f.fm = _fm * frac.fz;[f reduceFraction];return f;
}//比较大小
-(Fraction *)maxValue:(Fraction *)frac{Fraction * f = [[Fraction alloc]init];_fz = _fz * frac.fm;frac.fz = _fm * frac.fz;f.fz = ( _fz > frac.fz ? _fz : frac.fz);f.fm = _fm * frac.fm;[f reduceFraction];return f;
}//打印分数
-(void)printFraction{if (_fz * _fm >= 0) {NSLog(@"两分数运算结果为:%ld/%ld",_fz,_fm);}else{NSLog(@"两分数运算结果为:-%ld/%ld",labs(_fz),labs(_fm));}
}
这篇关于求两个分数的加减乘除,并比较大小的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!