devxlogo

Using Complex Numbers

Using Complex Numbers

The C++ standard library can handle complex numbers. Complex numbers may be used by including . The class std::complex is defined as a template, allowing complex numbers to use different value types, such as float and double.

You can construe complex numbers using the real and imaginary components; you can also construe them using the polar() function. For example:

std::complex 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.

See also  How to Avoid Money Transfer Scams  
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist