找出正方形面積的 Java 程式


給出正方形的各個邊的長度為l,編寫一個 Java 程式來求其面積。正方形是一個長方形,且其長和寬相同。因此,這種型別的長方形的面積為其長度的平方。

要使用 Java 計算正方形的面積,只需將給定的正方形長度乘以其自身的長度,並將結果儲存在另一個變數中。


Java 程式求正方形面積

下面是一個 Java 程式,說明如何求正方形的面積

public class AreaOfSquare {
   public static void main(String args[]){
      int length, area;
      // length of the square
      length = 55;
      System.out.println("Length of the square:: " + length);
      // calculating area 
      area = length * length;
      // printing the result
      System.out.println("Area of the square is:: " + area);
   }
}

輸出

Length of the square:: 55
Area of the square is:: 3025

Java 函式求正方形面積

在這個示例中,我們藉助使用者定義的函式來計算正方形的面積。

public class AreaOfSquare {
   // defining a method to calculate area 
   public static void calcAr(int l) {
      int area = l * l;
      System.out.println("Area of the square is:: " + area);    
   } 
   public static void main(String args[]){
      int length = 33;
      System.out.println("Length of the square:: " + length);
      // calling the method
      calcAr(length);
   }
}

輸出

Length of the square:: 33
Area of the square is:: 1089

更新日期:11 日 -9 月 -2024

7K+ 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告