我作為一個初學者,剛開始有很多的不懂,跟一張白紙一樣,在學到複數也就是complex的時候,照着書上抄了一段

編譯了下面一段代碼,結果顯示出錯。(書名《C語言入門經典第四版》)
代碼如下:
#include <iostream>
#include <complex>
int main()
{
using namespace std;
double complex z1 = 1.0 + 2.0 * I;;
double real_part = creal(z1);
double imag_part = cimag(z1);
cout<<real_part<<"\t"
<<imag_part<<endl;
}
運作結果當然是出錯了。
然後我廢了好大功夫才找到方法,是書寫方面的不規範,
代碼如下:
// complex_complex.cpp
// compile with: /EHsc
#include <complex>
#include <iostream>
int main()
{
using namespace std;
double pi = 3.14159265359;
// The first constructor specifies real & imaginary parts
complex <double> c1(4.0, 5.0);
cout << "Specifying initial real & imaginary parts,"
<< "c1 = " << c1 << endl;
// The second constructor initializes values of the real &
// imaginary parts using those of another complex number
complex <double> c2(c1);
cout << "Initializing with the real and imaginary parts of c1,"
<< " c2 = " << c2 << endl;
// Complex numbers can be initialized in polar form
// but will be stored in Cartesian form
complex <double> c3(polar(sqrt((double)8), pi / 4));
cout << "c3 = polar ( sqrt ( 8 ) , pi / 4 ) = " << c3 << endl;
// The modulus and argument of a complex number can be recovered
double absc3 = abs(c3);
double argc3 = arg(c3);
cout << "The modulus of c3 is recovered from c3 using: abs ( c3 ) = "
<< absc3 << endl;
cout << "Argument of c3 is recovered from c3 using:\n arg ( c3 ) = "
<< argc3 << " radians, which is " << argc3 * 180 / pi
<< " degrees." << endl;
}
這才成功的。
希望對初學者有幫助。