/*
6.设计一个类Circle,用来表示二维平面中的圆
1> 属性
* double _radius (半径)
* Point2D *_point (圆心)
2> 方法
* 属性相应的set和get方法
* 设计一个对象判断跟其他圆是否重叠(重叠返回YES,否则返回NO)
* 设计一个类方法判断两个圆是否重叠(重叠返回YES,否则返回NO)
*/
#import<Foundation/Foundation.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;
}
//计算跟其他点之间的距离
- (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 distace2;
return distace;
}
//计算两个点之间的距离
+ (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);
return distace;
}
@end
@interface Circle : NSObject
{
//半径
double _radius;
//圆心
Point2D *_point;
}
//半径的set和get操作
- (void)setRadius:(double)newRadius;
- (double)radius;
//圆心的set get操作
- (void)setPoint:(Point2D*)point;
- (Point2D*)point;
//计算两个元是否重叠
- (double)fadeOrNot:(Circle*)p1;
+ (double)fadeOrNotWithCircle1:(Circle*)p1 andCircle2:(Circle*)p2;
@end
@implementation Circle
//半径的set和get操作
- (void)setRadius:(double)newRadius
{
_radius = newRadius;
}
- (double)radius
{
return _radius;
}
//圆心的set get操作
- (void)setPoint:(Point2D*)point
{
_point = point;
}
- (Point2D*)point
{
return _point;
}
//计算两个元是否重叠
- (double)fadeOrNot:(Circle*)c1
{
//方法二
double length3 = [Circle fadeOrNotWithCircle1:self andCircle2:c1];
return length3;
}
+ (double)fadeOrNotWithCircle1:(Circle*)c1 andCircle2:(Circle*)c2
{
//方法一
double length = [[c1 point] calDistanceWithPoint:[c2 point]];
//圆心间的距离
NSLog(@"圆心间的距离为%f",length);
double len = [c1 radius] + [c2 radius];
//半径之和为
NSLog(@"半径之和为:%f",len);
return length - len;
}
@end
int main()
{
Point2D *p = [Point2D new];
//设置一个点
[p setXYWithX:2 andY:0];
Circle *c = [Circle new];
//设置半径
[c setRadius:1];
//设置圆心
[c setPoint:p];
Point2D *p1 = [Point2D new];
//设置一个点
[p1 setXYWithX:5 andY:0];
Circle *c1 = [Circle new];
//设置半径
[c1 setRadius:1];
//设置圆心
[c1 setPoint:p1];
double length = [c fadeOrNot:c1];
NSLog(@"%f",length);
length>0?NSLog(@"无重叠区域"):NSLog(@"有重叠区域");
}
IOS学习--课后练习6
最新推荐文章于 2024-09-06 09:27:24 发布