Java中計算多邊形面積的更巧妙演算法


“多邊形”一詞源於希臘語,其中“Poly”意為“多”,而“gon”意為“角”。多邊形是由連線三個或三個以上直線形成的二維封閉平面圖形。例如,三角形、四邊形、六邊形等等。

雖然有很多方法可以找到多邊形的面積,但這篇文章將使用一種更巧妙的演算法。

計算多邊形面積的巧妙演算法

巧妙演算法

你需要知道兩點:第一,根據數學約定,向上方向的y值始終為正;第二,根據計算機系統,向下方向的y值始終為正。該演算法透過使用正向下y座標逆時針列出頂點,提供了一種有效的解決方案。它將抵消這兩個事實,從而得到正面積。

現在讓我們討論一個實現巧妙演算法的Java程式。

演算法

  • 步驟 1 − 建立一個名為“Slicker”的類及其兩個內部類“Coordinates”和“Poly”。

  • 步驟 2 − 宣告並初始化一個常量“MAXIMUM”來限制多邊形的邊數。

  • 步驟 3 − 在內部類“Poly”中建立一個“Coordinates”類物件的陣列。然後,建立“Poly”類的建構函式以將座標儲存到該物件陣列中。

  • 步驟 4 − 進一步定義一個名為“calcAr”的方法以及引數“cr”。在這個方法中,我們將建立一個for迴圈,該迴圈將執行到多邊形的邊數並計算面積。

  • 步驟 5 − 現在,在main方法中,建立一個“Poly”類的物件“cr”。然後,我們將透過使用者輸入多邊形的邊數和座標。

  • 步驟 6 − 最後,我們將呼叫“calcAr”方法,並使用if-else塊檢查面積是正數還是負數。如果是正數,則執行“if”塊語句,否則執行else塊。

示例

import java.util.*;
public class Slicker {
   // to signify maximum number of sides of polygon
   static final int MAXIMUM = 50; 
   static class Coordinates {
      double c1, c2; 
      // declaring coordinates
   }
   static class Poly {
      // Array object of class Coordinates
      Coordinates cr[] = new Coordinates[MAXIMUM];
      int sides;
      Poly() 
      // constructor
      {
         // to accept input of coordinates
         for (int i = 0; i < MAXIMUM; i++)
         cr[i] = new Coordinates();
      }
   }
   // method to calculate area
   static double caclAr(Poly cr) {
      double res = 0;
      for (int i = 0; i < cr.sides; i++) {
         int j = (i + 1) % cr.sides;
         res += (cr.cr[i].c1 * cr.cr[j].c2)
          - (cr.cr[j].c1 * cr.cr[i].c2);
      }
      return res / 2;
   }
   static public void main(String[] args)
   {
      Poly cr = new Poly(); 
      // object of class 'Poly'
      // Object of scanner class for User inputs
      Scanner in = new Scanner(System.in);
      System.out.print("Enter total number of sides: ");
      cr.sides = in.nextInt();
      // to take coordinates from user
      System.out.println("Enter c1 and c2 coordinates: ");
      for (int i = 0; i < cr.sides; i++) {
         cr.cr[i].c1 = in.nextDouble();
         cr.cr[i].c2 = in.nextDouble();
      }
      // calling user defined method
      double caclAr = caclAr(cr);
      if (caclAr > 0) {
         System.out.print("The area of given Polygon: " + caclAr);
      } else {
         System.out.print("The area of given Polygon: " + (caclAr * -1));
      }
   }
} 

輸出

Enter total number of sides: 4
Enter c1 and c2 coordinates: 
2 3
3 5
5 8
8 2
The area of given Polygon: 17.0

結論

任何平面圖形都不能被認為是多邊形,例如圓,雖然它是一個封閉的平面圖形,但它沒有任何邊。所以我們不能稱之為多邊形。在這篇文章中,我們建立了一個Java程式,使用巧妙演算法計算多邊形的面積。

更新於:2023年5月12日

312 次瀏覽

開啟您的職業生涯

完成課程獲得認證

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