使用 C++ 中的复数来计算几何
在本节中,我们将学习如何使用 C++ 中标准模板库的复杂类制作点类。并将它们用于一些与几何相关的编程题。复数存在于标准模板库中的 complex 类中(包含头文件 <complex>)
Point 类定义
为了将复数转换为点,我们将把 complex<double> 的名称更改为 point,然后将 x 更改为 complex 类的 real(),并将 y 更改为 complex 类的 imag()。这样,我们就可以模拟 point 类了。
# 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 << "The point is :" << "(" << my_pt.x << ", " << my_pt.y << ")";
}输出
The point is :(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 << "The point is:" ;
print_point(my_pt);
cout << endl;
cout << "Distance of the point from origin:" << 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);
}输出
The point is:(6, 7) Distance of the point from origin: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)
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP