suranga
suranga

Reputation: 228

Initializing complex number array in C++

I need to create an array that consists of complex numbers. I used the following code to initialize it.

std::complex<double> Uf[2]={(1, 2),(3, 4)};

I am expecting Uf[0] to be 1 + 2*i and Uf[1] to be 3+ 4*i but when I debug the program, I found out that imaginary values are shown as real and surprisingly imaginary value is zero for both numbers (i.e. Uf[0] is real: 2.0000.. imag: 0.0000.... and Uf[1] is real: 4.0000.. imag: 0.0000.. . Can somebody explain me how to sort this out?

Thanks

Upvotes: 3

Views: 24557

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

It's because you're using the comma operator, so the complex values will be initialized with 2 and 4 respectively. Replace the parentheses with curly-braces instead:

std::complex<double> Uf[2]={{1, 2},{3, 4}};

If the above doesn't work, your compiler is not C++11 compatible, and you have to explicitly create the array complex members:

std::complex<double> Uf[2]={std::complex<double>(1, 2),std::complex<double>(3, 4)};

Upvotes: 12

yizzlez
yizzlez

Reputation: 8805

You are initializing the array wrong. Try this:

std::complex<double> Uf[2]={{1, 2},{3, 4}};

Upvotes: 3

Related Questions