Objective-C面向对象-如何在程序中使用多个分数

本文展示了如何在Objective-C中创建一个用于处理分数的类,通过实例化类并设置分数值来演示基本操作,并输出分数结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

范例3-3,在前文用于处理分数的Objective-C类中范例3-2的基础上,将一个分数设置成2/3,另外个设置成3/7,并且显示他们。代码对比只有 program 部分有变化。

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



最后分享下笔者在优快云上传的源代码链接: Fractions
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值