Objective-C程序设计 CH4.7

Code: (Objective-C)

  1. /* 
  2.  Programming in Objective-C, 4th edition 
  3.  Chapter 4 Exercise 7 
  4.  */  
  5.   
  6. #import <Foundation/Foundation.h>  
  7.   
  8. //---- @interface section ----  
  9.   
  10. @interface Rectangle: NSObject  
  11. -(void) setWidth: (int) w;  
  12. -(void) setHeight: (int) h;  
  13. -(int) width;  
  14. -(int) height;  
  15. -(int) area;  
  16. -(int) perimeter;  
  17.   
  18. @end  
  19.   
  20.   
  21. //---- @implementation section ----  
  22. @implementation Rectangle  
  23. {  
  24.     int width;  
  25.     int height;  
  26. }  
  27.   
  28. -(void) setWidth: (int) w  
  29. {  
  30.     width = w;  
  31. }  
  32. -(void) setHeight: (int) h  
  33. {  
  34.     height = h;  
  35. }  
  36.   
  37. -(int) width  
  38. {  
  39.     return width;  
  40. }  
  41.   
  42. -(int) height  
  43. {  
  44.     return height;  
  45. }  
  46.   
  47. -(int) area  
  48. {  
  49.     return (width * height);  
  50. }  
  51.   
  52. -(int) perimeter  
  53. {  
  54.     return (width + height) * 2;  
  55. }  
  56.   
  57. @end  
  58.   
  59.   
  60. //---- program section ----  
  61.   
  62. int main (int argc, char * argv[])  
  63. {  
  64.     @autoreleasepool {  
  65.           
  66.         Rectangle * rectA = [[Rectangle alloc] init];  
  67.           
  68.         // Set width and height of rectangle.  
  69.         [rectA setWidth: 3];  
  70.         [rectA setHeight: 5];  
  71.            
  72.          NSLog (@"Rectangle rectA has a width of %i and a height of %i.", [rectA width], [rectA height]);  
  73.            
  74.          NSLog (@"Area of rectA: %i", [rectA area]);  
  75.                     
  76.          NSLog (@"Perimeter of rectA: %i", [rectA perimeter]);  
  77.           
  78.         }  
  79.          return 0;  
  80. }  

Output:
Rectangle rectA has a width of 3 and a height of 5.
Area of rectA: 15
Perimeter of rectA: 16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值