如何在C中使用复数“i”

新手上路,请多包涵

我现在正在编写一个简单的 DFT 算法,我想在复指数中使用复数 i。 I saw somebody use #include<complex> and #include<cmath> , and then they used the overloaded symbol I such as exp(2*I) .但它似乎在我的 Visual Studio 编译器中不起作用。那么,任何人都可以举一个使用复指数的简单例子吗?谢谢!

原文由 Cancan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 851
2 个回答

这是一个简短的完整示例:

 #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;
}

用 g++ 测试

原文由 Floris 发布,翻译遵循 CC BY-SA 4.0 许可协议

另一种方法是在C++14之后使用 std::literals::complex_literals::operator""i

 #include <iostream>
#include <complex>

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

输出:

 c = (1,3)

原文由 Ayxan Haqverdili 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题