Objective-C类-对分数进行加法操作
来源:互联网 发布:常用控制算法 编辑:程序博客网 时间:2024/06/06 01:12
在这里和大家继续讨论前文《Objective-C 具有多个参数的方法》中的 Fraction 类。我们打算实现一个方法 add:,能够让一个分数与另一个分数相加,并把一个分数作为参数。这个方法的声明如下:
-(void) add: (Fraction *) f;
注意参数 f 的声明:
(Fraction *) f
这条语句说明 add: 方法的参数类型是 Fraction 类。星号是必需的!
[aFraction add: bFraction];
这个表达式将 Fraction bFraction 和 Fraction aFraction 相加。
现在我们快速回顾数学如何加 a / b + c / d,应转化为 (ad + bc) / bd,以下就是根据这个数据公式来写的 @implementation 部分的新方法代码:
01 // Add a Fraction to the receiver
02
03-(void) add: (Fraction *) f
04{
05 // To add two fractions:
06 // a / b + c / d = ((a * d) + (b * c)) / (b * d)
07
08 numerator = numerator * f.denominator + denominator * f.numerator;
09 denominator = denominator * f.denominator;
10}
02
03
04
05
06
07
08
09
10
接下来将 add: 方法在 main 中测试,构成范例 7-3:
01 #import "Fraction.h"
02
03int main (int argc, const char * argv[])
04{
05 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
06
07 Fraction *aFraction = [[Fraction alloc] init];
08 Fraction *bFraction = [[Fraction alloc] init];
09
10 // Set two fractions to 1/4 and 1/2 and add them together
11
12 [aFraction setTo: 1 over: 4];
13 [bFraction setTo: 1 over: 2];
14
15 // Print the results
16
17 [aFraction print];
18 NSLog(@"+");
19 [bFraction print];
20 NSLog(@"=");
21
22 [aFraction add: bFraction];
23 [aFraction print];
24
25 [aFraction release];
26 [bFraction release];
27
28 [pool drain];
29 return 0;
30}
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
最终输出结果如下:
1/4
+
1/2
=
6/8
CSDN 源代码地址
- Objective-C类-对分数进行加法操作
- Objective-C使用NSFileHandle类对文件进行基本操作,IOS文件操作
- Objective-C使用NSFileHandle类对文件进行基本操作,IOS文件操作
- 用于处理分数的Objective-C类
- Objective-C分数运算
- Objective-C 分数加减乘除
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对URL进行URLEncode编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- Objective-C 对 URL 进行 URLEncode 编码
- word
- 如何查找你的mac地址
- Objective-C类-Objective-C 合成存取器方法
- Objective-C类-Objective-C 具有多个参数的方法
- SQL Server 2008中使用FileStream存取大文件
- Objective-C类-对分数进行加法操作
- 缓存穿透与缓存雪崩
- linq实例 - Group的使用
- Objective-C类-Objective-C 局部变量简述
- Objective-C类-Objective-C 方法的参数
- DDraw笔记-创建表面
- Objective-C类-Objective-C 局部静态变量 static
- GridView开发积累
- Objective-C类-为分数类添加最大公约数方法