C++复数,什么是正确的格式

C++ complex numbers, what is the right format?

本文关键字:格式 复数 什么 C++      更新时间:2023-10-16

我想用C++处理复数。因此,我包含了#include <complex>。现在我的问题是:如何声明一个变量?(比如说,1 + i的格式是什么?)

提前感谢:-)

// 1 + 2i
std::complex<double> c(1, 2);

std::complex的构造函数有两个参数:

  • 第一,wich有数字的实数部分
  • 第二,维奇有数字的虚部

例如:

std::complex<float> my_complex(1,1); //1 + 1i 

此外,C++11引入了用户定义的文字,这使我们能够实现(或者由标准库实现,就像在这个C++14接受的提议中一样)一个易于使用的复数的文字:

constexpr std::complex<float> operator"" i(float d)
{
    return std::complex<float>{0.0L,static_cast<float>( d )};
}

您可以按如下方式使用:

auto my_complex = 1i; // 0 + 1i

通过指定模板参数并指定变量名称来定义变量,与大多数其他模板大致相同:

std::complex<double> x(1, 1);

ctor的第一个参数是实部,第二个参数是虚部。

从C++14开始,添加了一个用户定义的文字运算符,因此您可以用一种更自然的表示法初始化一个复杂的变量:

using namespace std::literals;
std::complex<double> c = 1.2 + 3.4i;

在这种情况下,(显然)1.2是实部,3.4是虚部。

试试这个:

#include <complex>
#include <iostream>
using namespace std;
int main()
{
    complex<double> a = {1,2};
    complex<double> b(3,4);
    cout << a + b << "n";
}

下面是一个如何使用的示例。它在QT 下编译和运行

#include <QCoreApplication>
#include<complex>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::complex<double> x=3.0-3.0i;
std::complex<double> y=2.0+4.0i;
cout.precision(3);
cout<<"x="<<x<<" y="<<y<<'n';
cout<<" OR x real="<<real(x)<<" x imagine="<<imag(x)<<"nn";
complex<double> sum = x + y;
cout<<"The sum: x + y = "<<sum<<'n';
complex<double> difference = x - y;
cout<<"The difference: x - y = "<<difference<<'n';
complex<double> product = x * y;
cout<<"The product: XY = "<<product<<'n';
complex<double> quotient = x / y;
cout<<"The quotient: x / y = "<<quotient<<'n';
complex<double> conjugate = conj(x);
cout<<"The conjugate of x = "<<conjugate<<'n';
complex<double> reciprocal = 1.0/x;
cout<<"The reciprocal of x = "<<reciprocal<<'n';
complex<double> exponential =exp(x);
cout<<"The exponential  of x = "<<exponential<<'n';
double magnitude=2.0,phase=45;
cout<<"magintude = "<<magnitude<<" phase = "<< phase<<" degreesn";
complex<double> pol= std::polar(2.0,(M_PI/180.0)*phase);
cout<<"The polar: x , y = "<<pol<<'n';
return a.exec();
}