Objective-C程序设计 CH4.6

Code: (Objective-C)

  1. // Chapter 4 Exercise 6.  
  2. // Complex numbers are numbers that contain two components:  
  3. // a real part and an imaginary part. If a is the real component  
  4. // and b is the imaginary component, this notation is used to  
  5. // represent the number:  
  6. //                      a+bi  
  7. //   
  8. // Write an Objective-C program that defines a new class called  
  9. // Complex. Following the paradigm established for the Fraction  
  10. // class, define the following methods for your new class:  
  11. //      -(void) setReal: (double) a;  
  12. //      -(void) setImaginary: (double) b;  
  13. //      -(void) print; // display as a + bi   
  14. //      -(double) real;  
  15. //      -(double) imaginary;  
  16. //  
  17. // Write a test program to test your new class and methods.  
  18.   
  19. #include <Foundation/Foundation.h>  
  20.   
  21. @interface Complex : NSObject   
  22.     -(void) setReal: (double) a;  
  23.     -(void) setImaginary: (double) b;  
  24.     -(void) print; // display as a + bi   
  25.     -(double) real;  
  26.     -(double) imaginary;  
  27. @end  
  28.   
  29. @implementation Complex  
  30. {  
  31.     double real, imaginary;  
  32. }  
  33.   
  34. -(void) setReal: (double) a  
  35. {  
  36.     real = a;  
  37. }  
  38.   
  39. -(void) setImaginary: (double) b  
  40. {  
  41.     imaginary = b;  
  42. }  
  43.   
  44. -(void) print  
  45. {  
  46.     NSLog(@"%f + %fi", real, imaginary);  
  47. }  
  48.   
  49. -(double) real  
  50. {  
  51.     return real;  
  52. }  
  53.   
  54. -(double) imaginary  
  55. {  
  56.     return imaginary;  
  57. }  
  58. @end  
  59.   
  60. int main(int argc, const char *argv[]) {  
  61.       
  62.     @autoreleasepool {  
  63.         Complex *myComplex = [[Complex alloc]init];  
  64.         [myComplex setReal: 5];  
  65.         [myComplex setImaginary: 10];  
  66.         [myComplex print];  
  67.     }  
  68.     return 0;  
  69. }  

Output: 
5.000000 + 10.000000i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值