objective-c第七章课后练习3
题:Fraction类对负分数适用吗?例如:1/4-1/2 能否显示成-1/4?
1 //--------类定义实现参考上篇随笔,此处需更改print方法和main主方法部分---------- 2 - (void) print: (BOOL) yesOrNo//打印 3 { 4 if (yesOrNo == YES) { 5 [self reduce]; 6 } 7 8 if (num < 0) 9 { 10 num = -num; 11 NSLog(@"-%i/%i",num,den); 12 } 13 else 14 { 15 NSLog(@"%i/%i",num,den); 16 } 17 } 18 19 - (Fraction *) subFraction: (Fraction *) f 20 { 21 Fraction *result = [[Fraction alloc]init]; 22 23 result.num = num * f.den - den * f.num; 24 result.den = den * f.den; 25 26 //[result reduce]; 27 28 return result; 29 30 } 31 32 33 #import <Foundation/Foundation.h> 34 #import "Fraction.h" 35 36 int main(int argc, const char * argv[]) { 37 @autoreleasepool { 38 Fraction *myF = [[Fraction alloc]init]; 39 Fraction *myF_2 = [[Fraction alloc]init]; 40 Fraction *myResult; 41 42 int i;//接受输入1或0 43 BOOL b;//布尔类型判断i的值 44 45 [myF setN:1 andSetD:4]; 46 [myF_2 setN:1 andSetD:2]; 47 48 NSLog(@"Need to Simple? 1 or 0");//提示输入1或0 49 scanf("%i",&i); 50 b = i;//将i值传给布尔类型的b判断是否对分数进行约简 51 52 myResult = [myF subFraction:myF_2];//减法 53 [myResult print:b]; 54 55 myResult = [myF mulFraction:myF_2];//乘法 56 //[myResult print]; 57 58 myResult = [myF divFraction:myF_2];//除法 59 [myResult print:b]; 60 61 //[myResult print]; 62 63 64 } 65 return 0; 66 }