Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาพื้นที่รูปหลายเหลี่ยมจากจุดกำหนด n จุด ใน C++


บทนำ

หาพื้นที่รูปหลายเหลี่ยม (Polygon) เมื่อทราบพิกัดจุดโค้ง n จุดตามลำดับ

สูตรพื้นที่ (Shoelace Formula)

Area = ½ |(x₁y₂ + x₂y₃ + ... + xₙy₁) - (x₂y₁ + x₃y₂ + ... + x₁yₙ)|

ตัวอย่างโค้ด C++

#include <iostream>
#include <math.h>
using namespace std;

double areaOfPolygon(double x[], double y[], int n) {
    double area = 0.0;
    int j = n - 1;
    for (int i = 0; i < n; i++) {
        area += (x[j] + x[i]) * (y[j] - y[i]);
        j = i;
    }
    return abs(area / 2.0);
}

int main() {
    double X[] = {0, 1, 4, 8};
    double Y[] = {0, 2, 5, 9};
    int n = sizeof(X) / sizeof(X[0]);
    cout << "The area is " << areaOfPolygon(X, Y, n);
    return 0;
}

ผลลัพธ์

The area is 3.5