计算2点之间的距离:
#import "Point2D.h"
#import <math.h>
@interface Point2D ()
{
double _x;
double _y;
}
//set和get方法
-(void)setX:(double)x;
-(double)x;
-(void)setY:(double)y;
-(double)y;
-(void)setX:(double)x andsetY:(double)y;
//计算距离方法
-(double)distanceWithOtherPoint:(Point2D *)point;
+(double)distanceWithPoint1:(Point2D *)point1 andPoint2:(Point2D *)point2;
@end
@implementation Point2D
//x
-(void)setX:(double)x{
_x = x;
}
-(double)x{
return _x;
}
//y
-(void)setY:(double)y{
_y = y;
}
-(double)y{
return _y;
}
-(void)setX:(double)x andsetY:(double)y{
[self setX:x];
[self setY:y];
}
-(double)distanceWithOtherPoint:(Point2D *)point{
//X^2
double xDelta = [self x]-[point x];
double xDeltaPF = pow(xDelta, 2);
//Y^2
double yDelta = [self y]-[point y];
double yDeltaPF = pow(yDelta, 2);
return sqrt(xDeltaPF+yDeltaPF);//开根号
}
+(double)distanceWithPoint1:(Point2D *)point1 andPoint2:(Point2D *)point2{
return [point2 distanceWithOtherPoint:point1];
}
int main(int argc, const char * argv[]) {
Point2D * p1 = [Point2D new];
Point2D * p2 = [Point2D new];
[p1 setX:10 andsetY:90];
[p2 setX:80 andsetY:67];
double distance = [Point2D distanceWithPoint1:p1 andPoint2:p2];
NSLog(@"distance=%f",distance);
return 0;
}
@end