How to use complex number "i" in C++

Another way is to use std::literals::complex_literals::operator""i after C++14:

#include <iostream>
#include <complex>

int main() {
    using namespace std::complex_literals;
    auto c = 1.0 + 3.0i;
    std::cout << "c = " << c << '\n';
}

Output:

c = (1,3)

Here is a short complete example:

#include <iostream>
#include <complex>
#include <cmath>

using namespace std;
typedef complex<double> dcomp;

int main() {
  dcomp i;
  dcomp a;
  double pi;
  pi = 2 * asin(1);
  i = -1;
  i = sqrt(i);
  a = exp(pi*i) + 1.+0i;
  cout << "i is " << i << "and Euler was right: exp(i pi) + 1 = " << a << endl;
} 

Tested with g++


I get this question recently as well and find a easy way for future reader:

Just use <complex> library like the following

#include <iostream>
#include <complex>
using namespace std ;

int main(int argc, char* argv[])
{
    const   complex<double> i(0.0,1.0);    
    cout << i << endl ;

    return(0) ;
}

You can find details here

A simple approach would be

#include <complex>

using std::complex;
const double pi = 3.1415;
void foo()
{
    complex<double> val(polar(1, pi/2.0); Create a complex from its olar representation
}