-3

锻炼:

“复数是包含两个分量的数字:实部和虚部。如果 a 是实部,b 是虚部,则使用此符号表示数字:a + bi 编写一个 Objective-C 程序定义了一个名为 Complex 的新类。按照为 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+bi作为格式说明符的结果强制执行%f。相反,您需要有两个参数,它们都ab分别传递给 NSLog 调用。因此,您将拥有:

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

最后,您的方法real应该imaginary是实例变量的“getter”,而不是打印到 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 回答