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
廣告