目标C编程Kochan第3章第4章练习6

时间:2012-08-12 14:35:48

标签: objective-c

练习:

“复数是包含两个组成部分的数字:真实部分和 想象的部分。如果a是真实分量而b是虚构分量,那么这个 符号用于表示数字: a + b i 编写一个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;
}

拜托,出了什么问题?

2 个答案:

答案 0 :(得分:1)

我可以看到一些明显的缺陷。首先,(这可能是复制/粘贴错误),您将interface拼错为iterface

其次,您的print方法无法正确写入NSLog。您试图强制将表达式a+bi作为格式说明符%f的结果。相反,您需要有两个参数,ab分别传递给NSLog调用。因此你有:

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

最后,您的方法realimaginary应该是实例变量的“getters”,而不是打印到NSLog的函数。因此,您只需要将函数体分别设为return a;return b;。对于前者(完整):

    -(double)real
    {
        return a;
    }

答案 1 :(得分: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;
}