text: Find the centroid of a non | C ++ program to implement the above approach ; For all vertices ; Calculate value of A using shoelace formula ; Calculating coordinates of centroid of polygon ; Driver code ; Coordinate of the vertices
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < double , double > find_Centroid ( vector < pair < double , double > > & v ) { pair < double , double > ans = { 0 , 0 } ; int n = v . size ( ) ; double signedArea = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { double x0 = v [ i ] . first , y0 = v [ i ] . second ; double x1 = v [ ( i + 1 ) % n ] . first , y1 = v [ ( i + 1 ) % n ] . second ; double A = ( x0 * y1 ) - ( x1 * y0 ) ; signedArea += A ; ans . first += ( x0 + x1 ) * A ; ans . second += ( y0 + y1 ) * A ; } signedArea *= 0.5 ; ans . first = ( ans . first ) / ( 6 * signedArea ) ; ans . second = ( ans . second ) / ( 6 * signedArea ) ; return ans ; } int main ( ) { vector < pair < double , double > > vp = { { 1 , 2 } , { 3 , -4 } , { 6 , -7 } } ; pair < double , double > ans = find_Centroid ( vp ) ; cout << setprecision ( 12 ) << ans . first << " ▁ " << ans . second << ' ' ; return 0 ; }