o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
幫我把這個 code 改成 c++ def polygon_area(coords): n = len(coords) area = 0 for i in range(n):…
- User
幫我把這個 code 改成 c++ def polygon_area(coords): n = len(coords) area = 0 for i in range(n): x1, y1 = coords[i] x2, y2 = coords[(i + 1) % n] # 下一个点,使用模运算使最后一个点与第一个点连接 area += x1 * y2 - x2 * y1 return abs(area) / 2
四個座標點
coordinates = [(0, 0), (231, 268), (8374, 2375), (974, 995)]
計算面積
area = polygon_area(coordinates) print(f"多邊形的面積是: {area:.2f}")
- Assistant
以下是將您提供的 Python 程式碼轉換為 C++ 的版本。這個程式使用 shoelace formula(鞋帶公式) 計算多邊形的面積,並輸出結果到小數點後兩位。
#include <iostream> #include <vector> #include <cmath> // 用於 abs 函數 #include <iomanip> // 用於設置輸出格式 using namespace std; // 定義一個結構來表示點的座標 struct Point { double x; double y; }; // 計算多邊形面積的函數 double polygon_area(const vector<Point>& coords) { int n = coords.size(); double area = 0.0; for(int i = 0; i < n; i++) { double x1 = coords[i].x; double y1 = coords[i].y; double x2 = coords[(i + 1) % n].x; // 下一个點,使用模運算使最後一點與第一點連接 double y2 = coords[(i + 1) % n].y; area += (x1 * y2 - x2 * y1); } return abs(area) / 2.0; } int main(){ // 定義四個座標點 vector<Point> coordinates = { {0, 0}, {231, 268}, {8374, 2375}, {974, 995} }; // 計算面積 double area = polygon_area(coordinates); // 設置輸出格式為固定小數點,並顯示兩位小數 cout << fixed << setprecision(2); // 輸出結果 cout << "多邊形的面積是: " << area << endl; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.