C++复数,什么是正确的格式
C++ complex numbers, what is the right format?
我想用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();
}
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 将"打开的CV图像"中的"颜色"转换为整数格式
- TDateTime格式在C++Builder中不会更改
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 检查不带转换的扫描格式
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- 是否可以从格式字符串中检索"width"
- clang格式:宏的缩进
- clang格式:禁用排序包含
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 将RGB图像保存为PPM格式
- 询问在设计我的手臂模拟器功能表示格式1
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 如何将strftime中的格式错误作为异常捕获
- 将CHW格式的浮点向量转换为cv::Mat
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 如何以叮当格式设置评论的行长?
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- C++复数,什么是正确的格式