The C++ standard library can handle complex numbers. Complex numbers may be used by including
You can construe complex numbers using the real and imaginary components; you can also construe them using the polar() function. For example:
cf(1); // 1 + 0istd::complex cd(2, 3); // 2 + 3istd::complex cld = std::polar (4, 5); // 4 e^(5i)
Obtain the magnitude, argument, and square of the magnitude using the abs(), arg(), and norm() member functions. For example:
std::cout << cd.abs() << ' ' << cd.arg() << ' ' << cd.norm() << std::endl;
Read complex numbers from std::cin and write them to std::cout. For example:
std::cin >> cd;std::cout << cd << std::endl;
Complex numbers may be in the following three formats for std::cin:
- 1 (meaning 1 + 0i)
- (2) (meaning 2 + 0i)
- (3,4) (meaning 3 + 4i)
Ignore any whitespace during input. Complex numbers are always output in the third format by std::cout.
Arithmetic operators such as +, -, *=, and /= work as expected for complex numbers. So do transcendental functions such as sin, cosh, exp, log, pow, and sqrt.