-3

エクササイズ:

「複素数は、実部と虚部の 2 つの成分を含む数です。a が実部で b が虚部の場合、この表記法を使用して数を表します: a + bi Fraction クラスで確立されたパラダイムに従って、新しいクラスに次のメソッドを定義します。

-(void) setReal: (double) a;
-(void) setImaginary: (double) b;
-(void) print; // display as a + bi
-(double) real;
-(double) imaginary;

新しいクラスとメソッドをテストするテスト プログラムを作成してください。」

うまくいかない私の解決策は次のとおりです。

    #import <Foundation/Foundation.h>

@iterface Complex:NSObject
{
    double a, b;
}

-(void)setReal: (double) a;
-(void)setImaginary: (double) b;
-(void) print;
-(double) real;
-(double) imaginary;

@end

@implementation Complex
-(void)setReal
{
    scanf(@"Set real value %f",&a);
}
-(void)setImaginary
{
    scanf(@"Set imaginary value %f", &b);
}
-(void) print
{
    Nslog(@"Your number is %f",a+bi);
}
-(double)real
{
    Nslog(@"Real number is %f",a);
}
-(double)imaginary
{
    NSlog(@"Imaginary number is %f",b)
}

@end



int main (int argc, char *argv[])
{
    NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
    Complex*num=[[complex alloc] init];
    [num setReal:3];
    [num setImaginary:4];
    Nslog(@"The complex number is %i",[num print]);
    [num release];
    [pool drain];
    return 0;
}

お願いします、何が悪いのですか?

4

2 に答える 2

1

私が見ることができるいくつかの明らかな欠陥があります。まず、(これはコピー/貼り付けのエラーである可能性があります)、スペルinterfaceiterface.

次に、printメソッドが NSLog に正しく書き込まれません。a+biformat specifier の結果として式を強制しようとしています%f。代わりに、2 つの引数が必要になり、両方が NSLog 呼び出しに別々に渡されますabしたがって、次のようになります。

    NSLog(@"Your number is %f + %fi", a, b);

最後に、メソッドrealimaginaryは、NSLog に出力する関数ではなく、インスタンス変数の「ゲッター」である必要があります。return a;したがって、代わりに、関数本体をそれぞれおよびにしたいだけですreturn b;。前者の場合 (完全):

    -(double)real
    {
        return a;
    }
于 2012-08-12T14:53:32.323 に答える
0

修正後の答えは次のとおりです。

#import <Foundation/Foundation.h>

@interface Complex: NSObject
{
    double real, imaginary;
}

-(void)setReal: (double) a;

-(void)setImaginary: (double) b;

-(void) print;

-(double) real;

-(double) imaginary;

@end

@implementation Complex


-(void)setReal: (double) a
{
    real =a; 
}



-(void)setImaginary: (double) b

{
    imaginary = b;
}



-(void) print
{
    NSLog(@"Your number is %.2f+%.2fi", real, imaginary);
}


-(double)real
{
    return real;
}



-(double)imaginary
{
    return imaginary;
}

@end



int main (int argc, char *argv[])
{

     NSAutoreleasePool*pool=[[NSAutoreleasePool alloc] init];

Complex *myComplex=[[Complex alloc] init];

[myComplex setReal:3];
[myComplex setImaginary:4];
[myComplex print];

[myComplex release];
[pool drain];


    return 0;
}
于 2012-08-12T23:22:23.953 に答える