2013-07-04 15 views
1

中的方法參數中表示虛數表示「nan」和「nani」正顯示在我的輸出中。我發現這代表「不是一個數字」,但我無法知道我出錯的地方,以及我的問題在於我對Objective-C或虛數或其他內容缺乏瞭解。如何在Objective-C

任何幫助或指針將不勝感激!

謝謝。

#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; 
} 

回答

0

的主要問題是在這裏:

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

sqrt(-1)結果是NaNsqrt()沒有任何意義的迴歸 「複雜」 的數字。

要設置Complex對象的虛部,您只需設置

[complex1 setImaginary: 3]; 

setImaginary:需要一個double的說法,這是有道理的,因爲複數的虛部是真正號)。

注:我不知道你想達到你的print方法是什麼,但它並不 打印a + bi如程序頂部所述。

+0

Martin,非常感謝您的回覆。我試圖回答S.Kochan在Objective-C中編程的練習4.6。我感覺我可能誤解了前幾章中的內容,需要返回並修改「打印」方法部分。感謝您的幫助 - 從沒有以前的編程知識,並試圖通過一本書(很好,因爲它沒有提供答案)是很難的! – VioladaGamba

+0

@VioladaGamba:不客氣。我沒有那本書,所以我不能告訴你什麼是預期的。也許'print'應該只是打印對象的描述:'NSLog(@「%f +%fi」,real,imaginary)'?你還應該看看Objective-C的「屬性」,目前的編譯器可以自動創建setter/getter方法。 - 請注意,您可以通過單擊複選標記來「接受」幫助解答。這標誌着問題已經解決,併爲您和答案的作者提供了一些聲譽點。祝你的項目好運! –

+0

非常感謝,今天剛剛參加這個論壇,並且非常感謝。非常感謝您的建議和幫助。現在明白我出錯的地方了。將檢查Ob-C「屬性」。 – VioladaGamba

1

你的NaNs來自sqrt(-1)

你想實現自己的複雜類型嗎? C99增加了他們,所以,除非您使用的是古老的Objective-C編譯器,你就可以做這樣的事情:

#include <complex.h> 

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

有一個在GNU libc的手冊一些有用的文檔和示例:Complex Numbers

+0

馬特,感謝您的幫助和鏈接 - 看起來不錯。我可以看到,在我之前,我的學習曲線比我最初意識到的更加陡峭 - 在那裏沒有什麼驚喜。克萊爾 – VioladaGamba