本帖最后由 S970028126 于 2015-6-25 09:55 编辑
1> 属性:
double _x
double _y
2> 方法:
属性相应的set和get方法
设置一个对象方法同时设置x和y
设置一个对象方法计算跟其他点的距离
设计一个类方法计算两个点之间的距离
3> 提示
c语言的math.h中有个函数,double pow(double n, double m);计算n的m次方
c语言中math.h中有个函数:double sqrt(double n);计算根号n的值
# import <Foundation/Fountatin.h>
# import <math.h>
//点
@interface Point2D : NSObject
{
double _x; // x值
double _y; // y值
}
//x值的getter和setter
- (void)setX: (double)x;
- (double)x;
//y值的getter和setter
- (void)setY: (double)y;
- (double)y;
//同时设置x和y
- (void)setX: (double)x andY: (double)y;
//设置一个对象方法计算跟其他点的距离
- (double)distanceWithOther: (Point2D *)other;
//设计一个类方法计算两个点之间的距离
+ (double)distanceBetweenPoint1: (Point2D *)p1 andPoint2: (Point2D *)p2;
@end
@implementation Point2D
//x值的getter和setter方法
- (void)setX: (double)x
{
_x = x;
}
- (double)x
{
return _x;
}
//y值的getter和setter
- (void)setY: (double)y
{
_y = y;
}
- (double)y
{
return _y;
}
//同时设置x和y
- (void)setX: (double)x andY: (double)y
{
_x = x;
_y = y; //或
self->_x = x;
self->_y = y;// 或
[self setX:x];
[self setY:y];//这种方法好
}
//设置一个对象方法计算跟其他点的距离
- (double)distanceWithOther: (Point2D *)other
{
return [Point2D distanceBetweenPoint1: self andPoint2: other];
}
//设计一个类方法计算两个点之间的距离
+ (double)distanceBetweenPoint1: (Point2D *)p1 andPoint2: (Point2D *)p2
{
double xDelta = [p1 x] -[p2 x];
double xDelaPF = pow(xDelta, 2);
double yDelta = [p1 y] -[p2 y];
double yDelaPF = pow(yDelta, 2);
return sqrt(xDeltaPF + yDeltaPF);
}
@end |
|