Error with finding area of the intersection of two rectangles (objective-c) -
i make program, find area of the intersection of 2 rectangles. have height, width , coordinates of rectangles.
but wont work! xcode terminates program "thread 1: signal sigabrt" on line (rectangle.m):
reswidth = (origin.x + width) - (second.origin.x + second.width);
so, here's code:
main.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;
}
rectangle.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
rectangle.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
thanks!!!!
you did not implement method -(xypoint*) origin
in rectangle class, crash when second.origin
. make origin property in rectangle class , should work. don't use new method much, it's bad practice , stops seeing other init methods might implemented
Comments
Post a Comment