我做了一个程序,它会找到两个矩形相交的区域。我有这个矩形的高度、宽度和坐标。
但它不会工作!Xcode 在此行 (Rectangle.m) 上使用“Thread 1: SIGNAL SIGABRT”终止程序:
reswidth = (origin.x + width) - (second.origin.x + second.width);
所以,这是我的代码:
主.m:
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "XYPoint.h"
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [NSAutoreleasePool new];
Rectangle *myrect1 = [Rectangle new];
Rectangle *myrect2 = [Rectangle new];
XYPoint *temp = [XYPoint new];
[temp setX: 200 andY: 420];
[myrect1 setOrigin:temp];
[temp setX: 400 andY: 300];
[myrect2 setOrigin:temp];
[temp dealloc];
[myrect1 setWidth:250 andHeight:75];
[myrect2 setWidth:100 andHeight:180];
double print = [myrect1 intersect:myrect2];
NSLog(@"%g", print);
[pool drain];
return 0;
}
矩形.h:
#import <Foundation/Foundation.h>
#import "XYPoint.h"
@interface Rectangle : NSObject
{
double width;
double height;
XYPoint *origin;
}
@property double width, height;
-(XYPoint *) origin;
-(void) setOrigin: (XYPoint *) pt;
-(void) setWidth: (double) w andHeight: (double) h;
-(double) area;
-(double) perimeter;
-(double) intersect: (Rectangle *) second;
@end
矩形.m:
#import "Rectangle.h"
@implementation Rectangle
@synthesize width, height;
-(void) setOrigin:(XYPoint *)pt
{
origin = [[XYPoint alloc] init];
[origin setX: pt.x andY: pt.y];
}
-(void) setWidth: (double) w andHeight: (double) h
{
width = w;
height = h;
}
-(double) area
{
return width * height;
}
-(double) perimeter
{
return (width + height) * 2;
}
-(double) intersect:(Rectangle *) second
{
double result,reswidth,resheight;
reswidth = (origin.x + width) - (second.origin.x + second.width);
if (reswidth<0) reswidth *= -1;
resheight = (origin.y + height) - (second.origin.y + second.height);
if (resheight<0) resheight *= -1;
result = reswidth * resheight;
if (result<0) result *= -1;
return result;
}
@end
XYPoint.h:
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
{
double x;
double y;
}
@property double x,y;
-(void) setX:(double) xVal andY: (double) yVal;
@end
XYPoint.m:
#import "XYPoint.h"
@implementation XYPoint
@synthesize x,y;
-(void) setX:(double) xVal andY: (double) yVal
{
x=xVal;
y=yVal;
}
@end
谢谢!!!!