o1-preview-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++ 的版本:
#include <iostream> #include <vector> #include <cmath> #include <iomanip> using namespace std; // 定義點的結構 struct Point { double x, y; }; // 計算多邊形面積的函數 double polygon_area(const vector<Point>& coords) { int n = coords.size(); double area = 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; }說明:
- 使用了
struct Point結構來表示點的座標,包含x和y兩個成員。 polygon_area函數接受一個Point型的向量coords,計算多邊形的面積。- 使用模運算 來確保最後一個點與第一個點相連,實現閉合多邊形的計算。
- 使用了
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.