Complex number types are defined in C99, which the modern version of Objective-C is a superset of. The actual syntax is like:
#include <complex.h>
...
complex double z = 2.7 + 3.4*I;
complex double w = 4.5 - 1.7*I;
complex double t = z*w;
printf("%g + %gi", creal(t), cimag(t));
That i
suffix is an extension coming from GCC. The compiler (clang) used by Xcode has most features being compatible with GCC, thus you can write 3.4i
and have no errors.
And for your questions,
- How does Objective-C know to add an "i" to complex numbers?
If you mean the output, no Objective-C does not know to add an "i". It prints the "i" only because you told it to
-(void) print
{
NSLog(@"%f + %fi", real, imaginary);
// ^
}
- if I turn "myComplex.imaginary = 7;" into "myComplex.imaginary = 7i;" the output for that line becomes 0.00000i
Because 7i is an imaginary number, and myComplex.imaginary
is a "double", thus a real number. The C standard recommends that, when converting between real and imaginary numbers, you'll get zero (C99 §G.4.2/1). Thus effectively what you've written is myComplex.imaginary = 0.0;
.
- if I add any other letter, the program will simply not run, why is this?
Actually you can write things like 7.0if
. Again, this is a C thing, which Objective-C has adapted. You are allowed to add an f
to turn a decimal number from the the default type "double" to "float", and GCC adds an extra feature that you can add an i
to turn a real number to an imaginary number. Other suffices like 7.0x
will cause the compiler to stop because it doesn't know what x
means.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…