黑马程序员技术交流社区

标题: oc基础视频中一道题 [打印本页]

作者: Harvey_ios    时间: 2015-5-8 18:19
标题: oc基础视频中一道题
设计一个类Point2D,用来表示二维平面的某个点
1> 属性
* double  _x;
* double _y;
2> 方法
* 属性相应的set和get方法
* 设计一个对象方法同时设置x和y的值
* 设计一个对象方法计算和其他点的距离
* 设计一个类方法计算两点之间的距离
这方法里面第二点该怎么实现呢?

作者: 大家叫我小祥子    时间: 2015-5-9 00:03
  1. Point2D.h文件中

  2. #import <Foundation/Foundation.h>

  3. @interface Point2D : NSObject
  4. @property double x;
  5. @property double y;

  6. - (void)setPointX:(int)x andPointY: (int)y;
  7. - (float)calculateDistanceWithOther:(Point2D *)point2D;
  8. + (float)calculatorDistance:(Point2D *)point2D andOther: (Point2D *) other;
  9. @end
复制代码


  1. //
  2. //  Point2D.m
  3. //  day04
  4. //
  5. //  Created by gxiangzi on 15/5/8.
  6. //  Copyright (c) 2015年 itcast. All rights reserved.
  7. //

  8. #import "Point2D.h"
  9. #import "math.h"

  10. @implementation Point2D
  11. - (void)setPointX:(int)x andPointY: (int)y
  12. {
  13.     self.x = x;
  14.     self.y = y;
  15. }

  16. - (float)calculateDistanceWithOther:(Point2D *)point2D
  17. {
  18.     float Xdistance = pow((self.x - point2D.x), 2);
  19.     float Ydistance = pow((self.y - point2D.y), 2);
  20.     return sqrt(Xdistance + Ydistance);
  21. }

  22. + (float)calculatorDistance:(Point2D *)point2D andOther: (Point2D *) other
  23. {
  24.     float Xdistance = pow((point2D.x - other.x), 2);
  25.     float Ydistance = pow((point2D.y - other.y), 2);
  26.     return sqrt(Xdistance + Ydistance);
  27. }
  28. @end
复制代码

  1. /*
  2. 5.设计一个类Point2D,用来表示二维平面中某个点
  3. 1> 属性
  4. * double x
  5. * double y

  6. 2> 方法
  7. * 属性相应的set和get方法
  8. * 设计一个对象方法同时设置x和y
  9. * 设计一个对象方法计算跟其他点的距离
  10. * 设计一个类方法计算两个点之间的距离

  11. 3> 提示
  12. * C语言的math.h中有个函数:double pow(double n, double m); 计算n的m次方
  13. * C语言的math.h中有个函数:double sqrt(double n); 计算根号n的值(对n进行开根)

  14. */

  15. #import <Foundation/Foundation.h>
  16. #import "Point2D.h"

  17. int main(int argc, const char * argv[]) {
  18.    
  19.     Point2D * p1 = [[Point2D alloc] init];
  20.     Point2D * p2 = [[Point2D alloc] init];
  21.    
  22.     [p1 setPointX:10 andPointY:10];
  23.     [p2 setPointX:20 andPointY:20];
  24.    
  25.     float f1 = [p1 calculateDistanceWithOther:p2];
  26.     NSLog(@"f1 = %.2f",f1);
  27.    
  28.     float f2 = [Point2D calculatorDistance:p1 andOther:p2];
  29.     NSLog(@"f2 = %.2f",f2);
  30.    
  31.     return 0;
  32. }
复制代码

作者: wangzhewjl    时间: 2015-5-9 09:40
这个是某一个课程的作业吧!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2