// Fraction.h #import <Foundation/Foundation.h> @interface Fraction : NSObject @property (nonatomic, assign)NSInteger above;//分子 @property (nonatomic, assign)NSInteger below;//分母 //初始化 - (id)initWithName:(NSInteger)above below:(NSInteger)below; //最大公约数 - (NSInteger)maxGY:(NSInteger)above below:(NSInteger)below; //约分 - (void)simply; //相加 - (void)sumfraction:(Fraction *)fraction; //相减 - (void)subfraction:(Fraction *)fraction; //相乘 - (void)mulfraction:(Fraction *)fraction; //相除 - (void)divfraction:(Fraction *)fraction; //输出 - (NSString *)description; @end
.m文件
// Fraction.m #import "Fraction.h" @implementation Fraction //初始化 - (id)initWithName:(NSInteger)above below:(NSInteger)below{ self = [super init]; if (self) { self.above = above; self.below = below; } return self; } //最大公约数 - (NSInteger)maxGY:(NSInteger)above below:(NSInteger)below{ NSInteger a = above % below; while (a != 0){ above = below; below = a; a = above % below; } return below; } //约分 - (void)simply{ NSInteger b = [self maxGY:self.above below:self.below]; self.above /= b; self.below /= b; } //相加 - (void)sumfraction:(Fraction *)fraction{ self.above = self.above * fraction.below + fraction.above * self.below; self.below = self.below * fraction.below; [self simply]; } - (void)subfraction:(Fraction *)fraction{ self.above = self.above * fraction.below - fraction.above * self.below; self.below = self.below * fraction.below; [self simply]; } - (void)mulfraction:(Fraction *)fraction{ self.above = self.above * fraction.above ; self.below = self.below * fraction.below; [self simply]; } - (void)divfraction:(Fraction *)fraction{ self.above = self.above * fraction.below ; self.below = self.below * fraction.above; [self simply]; } //输出 - (NSString *)description{ return [NSString stringWithFormat:@"%lu / %lu", self.above, self.below]; } @end
main.文件实现
// main.m #import <Foundation/Foundation.h> #import "Fraction.h" int main(int argc, const char * argv[]) { @autoreleasepool { //创建?个Fraction类(分数)实现分数的加减乘除,?较??、约分等?法。要求:为类添加属性 Fraction *fr1 = [[Fraction alloc]initWithName:2 below:4]; Fraction *fr2 = [[Fraction alloc]initWithName:3 below:5]; [fr1 sumfraction:fr2]; NSLog(@"%@",fr1); [fr1 subfraction:fr2]; NSLog(@"%@",fr1); [fr1 mulfraction:fr2]; NSLog(@"%@", fr1); [fr1 divfraction:fr2]; NSLog(@"%@", fr2); } return 0; }
仅供参考
时间: 2024-10-24 20:50:28