Objective-C类-对分数进行加法操作

在这里和大家继续讨论前文《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: over: 4];
13     [bFraction setTo: 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  源代码地
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值