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 }

接下来将 add: 方法在 main 中测试,构成范例 7-3:

01 #import "Fraction.h"
02 
03 int 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 }

最终输出结果如下:

1/4

+

1/2

=

6/8


CSDN 源代码地
原创粉丝点击