1

"nan" and "nani" is being displayed in my output. I have discovered that this stands for "not a number", but I am not able to see where I am going wrong, and whether my problem lies with my lack of understanding of Objective-C, or imaginary numbers, or something else.

Any help or pointers would be much appreciated!

Thanks.

#import <Foundation/Foundation.h>
@interface Complex: NSNumber

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

@end

@implementation Complex
{
    double real;
    double imaginary;
}
-(void) setReal: (double) a
{
    real = a;
}
-(void) setImaginary: (double) b
{
    imaginary = b;
}
-(void) print
{
    NSLog (@"%f x %fi = %f", real, imaginary, real * imaginary);
}
-(double) real
{
    return real;
}
-(double) imaginary
{
    return imaginary;
}
@end

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

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

        // Set real and imaginary values for first complex sum:
        [complex1 setReal: 2];
        [complex1 setImaginary: 3 * (sqrt(-1))];

        // Display first complex number sum with print method:
        NSLog (@"When a = 2 and b = 3, the following equation a x bi =");
        [complex1 print];

        //Display first complex number sum with getter method:
        NSLog (@"When a = 2 and b = 3, the following equation 
        a x bi = %f x %fi = %fi", [complex1 real], [complex1 imaginary], 
        [complex1 real] * [complex1 imaginary]);

    }
    return 0;
}
4

2 回答 2

1

你的 NaN 来自sqrt(-1).

您想实现自己的复杂类型吗?C99 添加了它们,因此除非您使用的是古老的 Objective-C 编译器,否则您将能够执行以下操作:

#include <complex.h>

double complex c = 3 * 2 I;
double r = creal(c);
double i = cimag(c);

GNU libc 手册中有一些有用的文档和示例:复数

于 2013-07-04T06:51:05.450 回答
0

主要问题在这里:

[complex1 setImaginary: 3 * (sqrt(-1))];

sqrt(-1)is的结果在任何意义上NaNsqrt()不会返回“复杂”数字。

要设置对象的虚部Complex,只需设置

[complex1 setImaginary: 3];

setImaginary:需要一个double参数,这是有道理的,因为复数的虚部是数。)

备注:我不知道你想用你的print方法实现什么,但它没有a + bi按照程序顶部的说明打印。

于 2013-07-04T06:48:53.107 回答