RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Complex Arithmetic Without Complexities-3 : Page 3

Creating and Initializing a Complex Number
You instantiate a complex number like this:

#include <complex>
using std:complex;

int main()
 complex <double> dc;
dc is an object that represents the complex number (0,0). By convention, a complex number is written as two comma-separated floating point numbers enclosed in parentheses. The first number is always the real part and the second is the imaginary part. To display the value of dc, use cout as usual:

cout<<dc<<endl; //display: (0,0)
This code will compile because the << manipulator has three overloaded versions—one for each std::complex<> specialization.

In a similar vein, use cin to read a complex number from the standard input:

cout<<"insert a complex, e.g., (10,-2)"<<endl;
By design, the constructor of std::complex is not explicit, and thus allows implicit conversions from floating point (and even integral) values to complex:

complex <double> compnum=5.9;
complex <double> anothercompnum=6;
After the initialization, compnum has the value (5.9,0) and anothercompnum is (5,0). Remember, when you initialize a complex object with a single initializer, that initializer is taken as the real part whereas the imaginary part defaults to 0. If the initializer is an integral value, it's implicitly converted to the floating point datatype of the specialization. In the example above, 6 is silently converted to double, which then becomes the real part of anothercompnum:

cout<<compnum<<endl; // <5.9,0>
cout<<anothercompnum<<endl; //<6,0>
Initialize a complex object with both the real and imaginary values like this:

complex<double> num2(-10.8,0.8); //(-10.8,0.8)

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date