我是编程和objective-c的新手(所以我可能会离开这里),我正在通过objective c第4版教科书进行编程,并且已经陷入其中一个练习。
谁能告诉下面的方法有什么问题?在我的程序中有一个矩形类,它具有设置它的宽度、高度和原点的方法(来自一个名为 XYPoint 的类)。
containsPoint 方法检查一个矩形的原点是否在另一个矩形内。当我测试此方法时,即使矩形确实包含该点,它也总是返回“否”。
intersects 方法将一个矩形作为参数 (aRect) 并在 if 语句中使用 containsPoint 方法来检查它是否与接收方相交,如果相交,则返回一个矩形,该矩形的原点位于相交处并具有正确的宽度和高度。
-(BOOL) containsPoint:(XYPoint *) aPoint
{
//create two variables to be used within the method
float upperX, upperY;
//assign them values, add the height and width to the origin values to range which the XYPoint must fall into
upperX = origin.x + height;
upperY = origin.y + width;
//if the value of aPoint's x and y points fall between the object's origin and the upperX or upperY values then the rectangle must contain the XYPoint and a message is sent to NSLog
if ((aPoint.x >= origin.x) && (aPoint.x <= upperX) && (aPoint.y >= origin.y) && (aPoint.y <= upperY) )
{
NSLog(@"Contains point");
return YES;
}
else
{
NSLog(@"Does not contain point");
return NO;
}
}
-(Rectangle *) intersects: (Rectangle *) aRect
{
//create new variables, Rectangle and XYPoint objects to use within the method
Rectangle *intersectRect = [[Rectangle alloc] init];
XYPoint *aRectOrigin = [[XYPoint alloc] init];
float wi, he; //create some variables
if ([self containsPoint:aRect.origin]) { //send the containsPoint method to self to test if the intersect
[aRectOrigin setX:aRect.origin.x andY:origin.y]; //set the origin for the new intersecting rectangle
[intersectRect setOrigin:aRectOrigin];
wi = (origin.x + width) - aRect.origin.x; //determine the width of the intersecting rectangle
he = (origin.y + height) - aRect.origin.y; //determine the height of the intersecting rectangle
[intersectRect setWidth:wi andHeight:he]; //set the rectangle's width and height
NSLog(@"The shapes intersect");
return intersectRect;
}
//if the test returned NO then send back these values
else {
[intersectRect setWidth:0. andHeight:0.];
[aRectOrigin setX:0. andY:0.];
[intersectRect setOrigin:aRectOrigin];
NSLog(@"The shapes do not intersect");
return intersectRect;
}
}
当我使用以下代码进行测试时
int main (int argc, char * argv [])
{
@autoreleasepool {
Rectangle *aRectangle = [[Rectangle alloc] init];
Rectangle *bRectangle = [[Rectangle alloc] init];
Rectangle *intersectRectangle = [[Rectangle alloc] init];
XYPoint *aPoint = [[XYPoint alloc] init];
XYPoint *bPoint = [[XYPoint alloc] init];
[aPoint setX:200.0 andY:420.00];
[bPoint setX:400.0 andY:300.0];
[aRectangle setWidth:250.00 andHeight:75.00];
[aRectangle setOrigin:aPoint];
[bRectangle setWidth:100.00 andHeight:180.00];
[bRectangle setOrigin:bPoint];
printf("Are the points within the rectangle's borders? ");
[aRectangle containsPoint: bPoint] ? printf("YES\n") : printf("NO\n");
intersectRectangle = [aRectangle intersects:bRectangle];
}
return 0;
}
我得到以下输出
Contains point
The origin is at 0.000000,0.000000, the width is 250.000000 and the height is 75.000000