Objective-C类-为分数类添加最大公约数方法

我们基于 《对分数进行加法操作》 一文中的范例 7-3,进一步完善分数类。上一次的计算,1/4 和 1/2 相加的结果显示为 6/8,而不是我们所期望的 3/4,这是因为加法例程只执行算术不做其他处理,它不会将结果相约。所以今天我们添加新的 reduce 方法。算法在之前的博文 《用 while 循环计算最大公因子》 已经提过,大家可以简单回顾下。

新添加的范例 7-4 reduce 方法如下:

01 -(void) reduce
02 {
03     int        numerator;
04     int        denominator;
05     int        temp;
06     
07     while (v != 0) {
08         temp v;
09         v;
10         temp;
11     }
12     
13     numerator /= u;
14     denominator /= u;
15 }

新的范例 7-4 main 函数:

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     
24     // Reduce the result of the addition and print the result
25     
26     [aFraction reduce];
27     [aFraction print];
28     
29     [aFraction release];
30     [bFraction release];
31     
32     [pool drain];
33     return 0;
34 }

最终输出结果:

1/4

+

1/2

=

3/4


很棒吧!我们的分数类又向前迈进了一步。CSDN 源代码地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值