中的方法參數中表示虛數表示「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;
}
Martin,非常感謝您的回覆。我試圖回答S.Kochan在Objective-C中編程的練習4.6。我感覺我可能誤解了前幾章中的內容,需要返回並修改「打印」方法部分。感謝您的幫助 - 從沒有以前的編程知識,並試圖通過一本書(很好,因爲它沒有提供答案)是很難的! – VioladaGamba
@VioladaGamba:不客氣。我沒有那本書,所以我不能告訴你什麼是預期的。也許'print'應該只是打印對象的描述:'NSLog(@「%f +%fi」,real,imaginary)'?你還應該看看Objective-C的「屬性」,目前的編譯器可以自動創建setter/getter方法。 - 請注意,您可以通過單擊複選標記來「接受」幫助解答。這標誌着問題已經解決,併爲您和答案的作者提供了一些聲譽點。祝你的項目好運! –
非常感謝,今天剛剛參加這個論壇,並且非常感謝。非常感謝您的建議和幫助。現在明白我出錯的地方了。將檢查Ob-C「屬性」。 – VioladaGamba