1

2 つの長方形の交点の面積を求めるプログラムを作成します。この長方形の高さ、幅、座標があります。

しかし、それはうまくいきません!Xcode は、次の行 (Rectangle.m) で「Thread 1: SIGNAL SIGABRT」でプログラムを終了します。

reswidth = (origin.x + width) - (second.origin.x + second.width);

だから、ここに私のコードがあります:

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

長方形.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

ありがとう!!!!

4

1 に答える 1

1

メソッドを矩形クラスに実装していないため、実装する-(XYPoint*) originとクラッシュしますsecond.origin。Origin を Rectangle クラスのプロパティにするだけで機能します。また、新しいメソッドをあまり使用しないでください。これは悪い習慣であり、実装されている可能性のある他の init メソッドが表示されなくなります。

于 2013-08-13T08:49:58.490 に答える