IOS学习--课后练习题5

/*
 5.设计一个类Point2D,用来表示二维平面中某个点
 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的值(对n进行开根)
 
 */


#import <Foundation/Foundation.h>
#import<math.h>


@interface Point2D : NSObject
{
    //横坐标
    double _x;
    //纵坐标
    double _y;
}


//横纵坐标的get和set方法
- (void)setX:(double)newX;


- (double)x;


- (void)setY:(double)newY;


- (double)y;


//同时设置x y
- (void)setXYWithX:(double)x andY:(double)y;


//计算跟其他点之间的距离
- (double)calDistanceWithPoint:(Point2D*)p1;


//计算两个点之间的距离
+ (double)calDistanceWithPoint1:(Point2D*)p1 andPoint2:(Point2D*)p2;


@end




@implementation Point2D


//横纵坐标的get和set方法
- (void)setX:(double)newX
{
    _x = newX;
}


- (double)x
{
    return _x;
}


- (void)setY:(double)newY
{
    _y = newY;
}


- (double)y
{
    return _y;
}


//同时设置x y
- (void)setXYWithX:(double)newX andY:(double)newY
{
    /*
    //第一种方法
    _x = newX;
    _y = newY;
     */
    /*
     //第二种方法
     self->x = newX;
     self->y = newY;
     */
    //第三种方法
    //最后一种方法最好,因为如果在方法setX中如果包含比较复杂的
    //语句(各种判断if)这样写可最大限度的避免重复代码
    [self setX:newX];
    [self setY:newY];
}


/*
 类方法和对象方法之间可以互相调用
 
 注意:
 一般情况下 类名后面都跟* 除了使用类名调用类方法是不跟*
 */


//计算跟其他点之间的距离
- (double)calDistanceWithPoint:(Point2D*)p1;
{
    //方法一、
    double xDistance,yDistace,distace;
    xDistance = pow((_x -[p1 x]),2);
    yDistace = pow((_y - [p1 y]),2);
    distace = sqrt(xDistance+yDistace);
    
    //方法二
    //int distace2 = [Point2D calDistanceWithPoint1:self andPoint2:p1];
    
    return distace;
    //return distace2;
    
}


//计算两个点之间的距离
+ (double)calDistanceWithPoint1:(Point2D*)p1 andPoint2:(Point2D*)p2
{
    //方法一
    double xDistance,yDistace,distace;
    xDistance = pow(([p1 x] - [p2 x]),2);
    yDistace = pow(([p1 y] - [p2 y]),2);
    distace = sqrt(xDistance+yDistace);
    
    //方法二
    //double distace = [p1 calDistanceWithPoint:p2];
    return distace;
    


}
@end


int main()
{
    Point2D *p = [Point2D new];
    Point2D *p1 = [Point2D new];
    /*
    [p setX:10];
    [p setY:10];
    
    NSLog(@"X=%f Y=%f",[p x],[p y]);
     */
    [p setXYWithX:3 andY:4];
    [p1 setXYWithX:0 andY:0];
    
   // NSLog(@"X=%f Y=%f",[p x],[p y]);
   //double XtoY = [p calDistanceWithX:0 andY:0];
    double XtoY = [p calDistanceWithPoint:p1];
    NSLog(@"XtoY=%f",XtoY);
    
    
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值