對於以下代碼,在Objective-C中已經定義了「複數」嗎?
- Objective-C知道如何將「i」添加到複數中?當我在Complex.m文件中將「real」和「imaginary」定義爲double值時,我認爲Xcode只會知道「real」和「imaginary」是double值。例如,如果我將「myComplex.imaginary = 7;」替換爲main.m文件中複數的結尾,到「myComplex.imaginary = 7i;」該行的輸出變爲0.00000i,如果我添加任何其他字母,程序將無法運行,這是爲什麼?
基本上我覺得Xcode已經知道「真實」和「虛構」的意思,但我沒有詳細說明這一點,所以我有點困惑。
另外,我應該注意,我沒有創建下面的代碼,因爲我無法自己弄清楚這個問題,這段代碼是從我的圖書論壇的成員中複製的。
// Complex.h
#include <Foundation/Foundation.h>
@interface Complex : NSObject
@property double real, imaginary;
-(void) print;
-(Complex *) add: (Complex *) complexNum;
-(Complex *) subtract: (Complex *) complexNum;
-(Complex *) multiply: (Complex *) complexNum;
-(Complex *) divide: (Complex *) complexNum;
@end
// Complex.m
#import "Complex.h"
@implementation Complex
@synthesize real, imaginary;
-(void) print
{
NSLog(@"%f + %fi", real, imaginary);
}
-(Complex *) add: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real + complexNum.real;
result.imaginary = imaginary + complexNum.imaginary;
return result;
}
-(Complex *) subtract: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real - complexNum.real;
result.imaginary = imaginary - complexNum.imaginary;
return result;
}
-(Complex *) multiply: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real * complexNum.real;
result.imaginary = imaginary * complexNum.imaginary;
return result;
}
-(Complex *) divide: (Complex *) complexNum
{
Complex *result = [[Complex alloc]init];
result.real = real/complexNum.real;
result.imaginary = imaginary/complexNum.imaginary;
return result;
}
@end
//
// main.m
// Complex
#include <Foundation/Foundation.h>
#import "Complex.h"
int main(int argc, const char *argv[]) {
@autoreleasepool {
Complex *myComplex = [[Complex alloc]init];
Complex *totalComplex = [[Complex alloc]init];
Complex *yourComplex = [[Complex alloc]init];
myComplex.real = 5.3;
myComplex.imaginary = 7;
[myComplex print];
NSLog(@"+");
yourComplex.real = 2.7;
yourComplex.imaginary = 4;
[yourComplex print];
NSLog(@"=");
totalComplex = [myComplex add: yourComplex];
[totalComplex print];
}
return 0;
}
哦,不!一個非易怒的英語中的n00b問題!發生了什麼事? (+1) – 2012-10-19 18:31:12