快樂2013年目標C對象的方法
我有一點與2個矩形的交集方法的問題,但我有一個問題,它不會讓我提前在這個題目跳閘。
我正在使用4個對象,2個點和2個矩形。 Point1是矩形1的原點,而Point2是矩形2的原點。
然後我調用矩形1的相交方法併發送矩形2對象以查看是否存在交集。
這裏的問題是,在方法內部,兩個矩形的原點都是相同的座標,因此,如果我沒有不同的原點,我不會得到好的信息。
這裏是我的.h文件:
@interface XYPoint : NSObject
@property int x,y;
-(void) setX:(int)xVal andY: (int) yVal;
@end
@interface Rectangle: graphicObject
@property float width, height;
- (void) setWidth:(float)w andHeight: (float) h;
- (void) setOrigin: (XYPoint *) pt;
- (bool) containsPoint: (XYPoint *) aPoint;
- (void) intersect: (Rectangle *) rect;
@end
這裏是我的.m文件:
@implementation XYPoint
@synthesize x,y;
-(void) setX:(int)xVal andY:(int)yVal;
{
x = xVal;
y = yVal;
}
@end
@implementation Rectangle
@synthesize width, height;
XYPoint *origin;
- (void) setWidth:(float) w andHeight: (float) h;
{
width = w;
height = h;
}
- (float) area
{
return width * height;
}
- (float) perimeter
{
return (2*width) + (2*height);
}
-(void) setOrigin: (XYPoint *) pt
{
if (! origin)
{
origin = [[XYPoint alloc]init];
}
origin.x = pt.x;
origin.y = pt.y;
}
- (XYPoint *) origin
{
return origin;
}
-(void) intersect: (Rectangle *) rect //
{
int pointCount;
pointCount = 0;
/* R1o R2o R1F R2F */
/* origin.x rect.origin.x origin.x+w rect.origin.x+w */
if ( (origin.x <= rect.origin.x) && (rect.origin.x <= (origin.x + width)) )
pointCount = pointCount +1;
NSLog(@"width = %g height = %g origin = (%d,%d)", width, height, origin.x, origin.y);
NSLog(@"rect.width = %g rect.height = %g rect.origin (%d,%d)", rect.width, rect.height, rect.origin.x, rect.origin.y);
if ( (rect.origin.x <= (origin.x + width)) && (origin.x + width <= rect.origin.x + rect.width) )
pointCount = pointCount + 1;
if ( (origin.y <= rect.origin.y) && (rect.origin.y <= (origin.y + height)))
pointCount = pointCount + 1;
if ( (rect.origin.y <= (origin.y + height) && (origin.y + height <= rect.origin.y + rect.height)))
pointCount = pointCount +1;
if (pointCount == 4)
NSLog (@"the rectangles intersect!");
else
NSLog (@"The rectangles don't intersect.");
}
@end
這是我的主要文件:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Rectangle * myRectangle1 = [[Rectangle alloc] init];
XYPoint * myPoint1 = [[XYPoint alloc]init];
[myPoint1 setX: 0 andY: 0];
[myRectangle1 setWidth: 3 andHeight: 3];
[myRectangle1 setOrigin : myPoint1];
Rectangle * myRectangle2 = [[Rectangle alloc] init];
XYPoint * myPoint2 = [[XYPoint alloc]init];
[myPoint2 setX: 2 andY: 2];
[myRectangle2 setWidth: 4 andHeight: 4];
[myRectangle2 setOrigin : myPoint2];
[myRectangle1 intersect: myRectangle2];
}
return 0;
}
我最後一次跑它,我有這個:
width = 3 hei GH T = 3原點=(2,2)
rect.width = 4 rect.height = 4 rect.origin(2,2)
矩形相交!
請參閱?兩個矩形都有相同的原點,儘管它們的設置都不相同。
非常感謝!
這只是一個智力練習,而且您故意不使用任何已經可用的幾何結構或函數? – jrturton
jrTurton:是的,它只是一個智力的例子,我是一個試圖爲了好玩而自己學習Objective-C的新手!謝謝。 –
然後玩得開心!祝你好運! – jrturton