我们基于 《对分数进行加法操作》 一文中的范例 7-3,进一步完善分数类。上一次的计算,1/4 和 1/2 相加的结果显示为 6/8,而不是我们所期望的 3/4,这是因为加法例程只执行算术不做其他处理,它不会将结果相约。所以今天我们添加新的 reduce 方法。算法在之前的博文 《用 while 循环计算最大公因子》 已经提过,大家可以简单回顾下。
新添加的范例 7-4 reduce 方法如下:
01 -(void) reduce
02 {
03 int u = numerator;
04 int v = denominator;
05 int temp;
06
07 while (v != 0) {
08 temp = u % v;
09 u = v;
10 v = temp;
11 }
12
13 numerator /= u;
14 denominator /= u;
15 }
02
03
04
05
06
07
08
09
10
11
12
13
14
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: 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
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 }
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
31
32
33
34
最终输出结果:
1/4
+
1/2
=
3/4
很棒吧!我们的分数类又向前迈进了一步。CSDN 源代码地址。