使用 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)

更新於:27-8-2020

223 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.