在本节中,我们将看到如何在C ++中使用STL中的复杂类制作点类。并将它们应用于一些与几何相关的问题。复数存在于STL的复杂类内部(#include <complex>)
为了使复数指向点,我们将complex <double>的名称更改为点,然后将x更改real()
为复杂类,将y更改imag()
为复杂类。因此,我们可以模拟点类。
# include <complex> typedef complex<double> point; # define x real()# define y imag()
我们必须记住,x和y用作宏,而不能用作变量。
让我们看下面的实现以更好地理解-
#include <iostream> #include <complex> using namespace std; typedef complex<double> point; #define x real()#define y imag()int main() { point my_pt(4.0, 5.0); cout << "关键是:" << "(" << my_pt.x << ", " << my_pt.y << ")"; }
输出结果
关键是:(4, 5)
为了应用几何,我们可以发现P到原点(0,0)的距离,表示为-abs(P)。OP与X轴之间的夹角,其中O为原点:arg(z)。P关于原点的旋转是P * polar(r,θ)。
让我们看下面的实现以更好地理解-
#include <iostream> #include <complex> #define PI 3.1415 using namespace std; typedef complex<double> point; #define x real()#define y imag()void print_point(point my_pt){ cout << "(" << my_pt.x << ", " << my_pt.y << ")"; } int main() { point my_pt(6.0, 7.0); cout << "关键是:" ; print_point(my_pt); cout << endl; cout << "点到原点的距离:" << abs(my_pt) << endl; cout << "Tangent angle made by OP with X-axis: (" << arg(my_pt) << ") rad = (" << arg(my_pt)*(180/PI) << ")" << endl; point rot_point = my_pt * polar(1.0, PI/2); cout << "Point after rotating 90 degrees counter-clockwise, will be: "; print_point(rot_point); }
输出结果
关键是:(6, 7) 点到原点的距离:9.21954 Tangent angle made by OP with X-axis: (0.86217) rad = (49.4002) Point after rotating 90 degrees counter-clockwise, will be: (-6.99972, 6.00032)