Can*_*can 5 c++ overloading complex-numbers complextype
我现在正在编写一个简单的DFT算法,我想在复指数中使用复数i.我看到有人使用#include<complex>和#include<cmath>,然后他们用重载符号I等exp(2*I).但它似乎在我的visual studio编译器中不起作用.那么,任何人都可以给出一个使用复指数的简单例子吗?谢谢!
小智 7
我最近也提到了这个问题,为未来的读者找到了一个简单的方法:
只需使用<complex>以下库
#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) ;
}
Run Code Online (Sandbox Code Playgroud)
另一种方式是std::literals::complex_literals::operator""i在C++14之后使用:
#include <iostream>
#include <complex>
int main() {
using namespace std::complex_literals;
auto c = 1.0 + 3.0i;
std::cout << "c = " << c << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出:
c = (1,3)
Run Code Online (Sandbox Code Playgroud)
这是一个简短的完整示例:
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
typedef complex<double> dcomp;
main() {
dcomp i;
dcomp a;
double pi;
pi = 2 * asin(1);
i = -1;
i = sqrt(i);
a = exp(2*pi*i);
cout << "i is " << i << "and Euler was right: e(i pi) = " << a << endl;
}
Run Code Online (Sandbox Code Playgroud)
用g ++测试