首页 > 代码库 > Objective-C 程序设计(第六版)第七章习题答案
Objective-C 程序设计(第六版)第七章习题答案
1.各个方法的实现
1 - (Fraction *) subtract: (Fraction *) f 2 { 3 Fraction *result = [[Fraction alloc] init]; 4 5 result.numerator = numerator *f.denominator - denominator *f.numerator; 6 result.denominator = denominator *f.denominator; 7 8 [result reduce]; 9 return result;10 }11 12 - (Fraction *) multiply: (Fraction *) f13 {14 Fraction *result = [[Fraction alloc] init];15 16 result.numerator = numerator *f.numerator;17 result.denominator = denominator *f.denominator;18 19 [result reduce];20 return result;21 }22 23 - (Fraction *) divide: (Fraction *) f24 {25 Fraction *result = [[Fraction alloc] init];26 27 result.numerator = numerator *f.denominator;28 result.denominator = denominator *f.numerator;29 30 [result reduce];31 return result;32 }
2.print方法
1 - (void) print: (BOOL) isReduce 2 { 3 if (numerator % denominator == 0) { 4 NSLog(@"%d",numerator/denominator); 5 }else if (isReduce) { 6 [self reduce]; 7 NSLog(@"%d / %d",numerator,denominator); 8 }else 9 NSLog(@"%d / %d",numerator,denominator);10 11 }
3.对负分数一样使用
1 int main(int argc, const char * argv[]) { 2 @autoreleasepool { 3 // insert code here... 4 5 Fraction *aFraction = [[Fraction alloc] init]; 6 Fraction *bFraction = [[Fraction alloc] init]; 7 Fraction *resultFraction; 8 9 [aFraction setTo:-1 over:4];10 [bFraction setTo:-1 over:2];11 12 resultFraction = [aFraction add:bFraction];13 14 15 [resultFraction print:YES];16 }17 return 0;18 }
4.
1 - (void) print: (BOOL) isReduce 2 { 3 if (numerator % denominator == 0) { 4 NSLog(@"%d",numerator/denominator); 5 }else if (numerator > denominator){ 6 [self reduce]; 7 NSLog(@"%d %d/%d",numerator/denominator,numerator % denominator,denominator); 8 }else if (isReduce) { 9 [self reduce];10 NSLog(@"%d/%d",numerator,denominator);11 }else12 NSLog(@"%d/%d",numerator,denominator);13 14 }
5.去掉synthesize合成方法后 修改变量名 _numerator, _denominator 替换程序中的numerator,denominator;增加setter方法 用于点语法。
6..m文件
1 - (Complex *) add: (Complex *) complexNum2 {3 Complex *result = [[Complex alloc] init];4 5 result.real = real + complexNum.real;6 result.imaginary = imaginary + complexNum.imaginary;7 8 return result;9 }
main
1 Complex * aComplex = [[Complex alloc]init]; 2 Complex * bComplex = [[Complex alloc]init]; 3 Complex * resultComplex; 4 5 6 [aComplex setReal:5.3]; 7 [aComplex setImaginary:7]; 8 [bComplex setReal:2.7]; 9 [bComplex setImaginary:4];10 resultComplex = [aComplex add:bComplex];11 12 NSLog(@"result is %.f + %.fi",[resultComplex real],[resultComplex imaginary]);13
7.略吧
Objective-C 程序设计(第六版)第七章习题答案
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。