ในบทความนี้ เราจะทำความเข้าใจวิธี คำนวณพื้นที่รูปสี่เหลี่ยมจัตุรัส (Square)
สูตร: พื้นที่ = ด้าน × ด้าน = ด้าน² (side²)
ตัวอย่าง Input และ Output
Input:
Length of the side : 4
Output:
Area of the square : 16
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร int my_side, my_area ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น ขั้นตอนที่ 4 - คำนวณพื้นที่ = my_side * my_side ขั้นตอนที่ 5 - แสดงผลลัพธ์ ขั้นตอนที่ 6 - หยุด
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class AreaOfSquare {
public static void main(String args[]) {
int my_side, my_area;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined");
System.out.print("Enter the length of a side : ");
my_side = my_scanner.nextInt();
my_area = my_side * my_side;
System.out.println("The area of the square is :" + my_area);
}
}
Output
Required packages have been imported A reader object has been defined Enter the length of a side : 4 The area of the square is :16
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class AreaOfSquare {
public static void main(String args[]) {
int my_side, my_area;
my_side = 4;
System.out.println("The length of the side of the square is defined as : " + my_side);
my_area = my_side * my_side;
System.out.println("The area of the square is :" + my_area);
}
}
Output
The length of the side of the square is defined as : 4 The area of the square is :16