How do I insert complex numbers into C++?

Asked

Viewed 183 times

2

I know I’ve asked a question like this before. It was about Python. But in C++, how to insert a complex number?

2 answers

2

In c++ you have the type Complex. It can be used as follows:

// 1 + 2i
std::complex<double> c(1, 2);

The constructor takes two parameters:

  • The first, the real part of the number
  • The second, the imaginary part

0

In C (it’s not in the question, but it’s in a tag) I do so

#include <complex.h>
#include <stdio.h>

int main(void) {
    complex double x, y, z;
    x = 3.14159 - 2*_Complex_I;
    y = 2.71828182 - _Complex_I;
    z = x - 2*y; printf("x - 2y = %f%+fi\n", creal(z), cimag(z));
}

You can see the code operating on ideone.

(In C++ I have no idea)

  • In some C11 implementations you can use macros CMPLX.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.