问题
I try to follow example from that website: http://en.cppreference.com/w/cpp/numeric/complex
But I get other results. For example for that code:
std::complex<double> z1 = 1i * 1i; // imaginary unit squared
std::cout << "i * i = " << z1 << '\n';
It works great, I get in the console:
i * i = (-1,0)
But other example:
std::complex<double> z3 = std::exp(1i * M_PI); // Euler's formula
std::cout << "exp(i * pi) = " << z3 << '\n';
I get error: call to 'exp' is ambiguous
So I tried that one:
double PI = std::acos(-1);
std::complex<double> z3 = pow(M_E, 1i * PI); // Euler's formula
std::cout << "exp(i * pi) = " << z3 << '\n';
And now I get no error, but the results are not expected:
exp(i * pi) = (1,0)
It should be minus 1, instead plus 1. Why it doesn't work for me. Please help.
Also other example:
std::complex<double> z4 = 1i + 1i; // Euler's formula
std::cout << "i + i = " << z4 << '\n';
I expect result: (0,2) But I get: (0,0)
I tried that code in xCode and in CodeBlocks. The same results. For any help thanks in advance.
My whole code looks like that:
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i; // it's OK
std::cout << "i * i = " << z1 << '\n'; // it gives: i * i = (-1.0,0.0)
/*
std::complex<double> z2 = std::pow(1i, 2); // That gives error: call to 'pow' is ambiguous'
std::cout << "pow(i, 2) = " << z2 << '\n';
double PI = std::acos(-1);
std::complex<double> z3 = std::exp(1i * PI); // That gives error: call to 'exp' is ambiguous'
std::cout << "exp(i * pi) = " << z3 << '\n';
*/
double PI = std::acos(-1);
std::complex<double> z4 = pow(M_E, 1i * PI);
std::cout << "exp(i * pi) = " << z4 << '\n'; // That gives: exp(i * pi) = (1.0,0.0). Should be (-1.0,0.0)
std::complex<double> z5 = 1. + 2i, z6 = 1. - 2i;
std::cout << "(1+2i)*(1-2i) = " << z5*z6 << '\n'; // That gives: (1+2i)*(1-2i) = (1.0,0.0). Should be (5.0,0.0)
std::complex<double> z7 = 1i + 1i;
std::cout << "i + i = " << z7 << '\n'; // That gives: i + i = (0.0,0.0). Should be (0.0,2.0)
return 0;
}
So as you can see, nothing complicated. Of course it's in main.cpp file, and in my project there are no other files.
来源:https://stackoverflow.com/questions/49116370/complex-1i-doesnt-work-properly