01
// Program to work with fractions - cont'd
02
03
#import <Foundation/Foundation.h>
04
05
//---- @interface section ----
06
07
@interface
Fraction
:
NSObject
08
{
09
int
numerator
;
10
int
denominator
;
11
}
12
13
-
(
void
)
print
;
14
-
(
void
)
setNumerator:
(
int
)
n
;
15
-
(
void
)
setDenominator:
(
int
)
d
;
16
17
@end
18
19
20
//---- @implementation section ----
21
22
@implementation
Fraction
23
24
-
(
void
)
print
25
{
26
NSLog
(
@"%i/%i"
,
numerator
,
denominator
);
27
}
28
29
-
(
void
)
setNumerator:
(
int
)
n
30
{
31
numerator
=
n
;
32
}
33
34
-
(
void
)
setDenominator:
(
int
)
d
35
{
36
denominator
=
d
;
37
}
38
39
@end
40
41
42
//---- program section ----
43
44
int
main
(
int
argc
,
const
char
*
argv
[])
45
{
46
NSAutoreleasePool
*
pool
=
[[
NSAutoreleasePool
alloc
]
init
];
47
Fraction
*
frac1
=
[[
Fraction
alloc
]
init
];
48
Fraction
*
frac2
=
[[
Fraction
alloc
]
init
];
49
50
// Set 1st fraction to 2/3
51
52
[
frac1
setNumerator:
2
];
53
[
frac1
setDenominator:
3
];
54
55
// Set 2nd fraction to 3/7
56
57
[
frac2
setNumerator:
3
];
58
[
frac2
setDenominator:
7
];
59
60
// Display the fractions
61
62
NSLog
(
@"First fraction is:"
);
63
[
frac1
print
];
64
65
NSLog
(
@"Second fraction is:"
);
66
[
frac2
print
];
67
68
[
frac1
release
];
69
[
frac2
release
];
70
71
[
pool
drain
];
72
return
0
;
73
}
最终输出结果:
First fraction is:
2/3
Second fraction is:
3/7