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);
    
    
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章