ในบทความนี้ เราจะเรียนรู้วิธีคำนวณเส้นรอบรูปสี่เหลี่ยมผืนผ้าในภาษา Java
สูตร
Perimeter = 2 × (length + width) = length + width + length + width
ตัวอย่างการทำงาน
อินพุต:
Length: 5, Width: 8
เอาต์พุต:
Perimeter: 26
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร float:
a, b, c, d, perimeter - รับค่าความยาวและความกว้างจากผู้ใช้ (ด้านตรงข้ามเท่ากัน จึงรับแค่ 2 ด้าน)
- คำนวณเส้นรอบรูป:
perimeter = a + b + c + d(โดย c=a, d=b) - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class RectanglePerimeter {
public static void main(String args[]) {
float a, b, c, d, perimeter;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A Scanner object has been defined");
System.out.print("Enter the length of first side: ");
a = my_scanner.nextFloat();
System.out.print("Enter the length of second side: ");
b = my_scanner.nextFloat();
c = a;
d = b;
System.out.printf("The length of the sides of the Rectangle are %.2f %.2f %.2f %.2f", a, b, c, d);
perimeter = a + b + c + d;
System.out.printf("\nThe perimeter of Rectangle is: %.2f", perimeter);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class RectanglePerimeter {
public static void main(String args[]) {
float a = 8, b = 5, c, d, perimeter;
c = a;
d = b;
System.out.printf("The length of the sides of the Rectangle are %.2f %.2f %.2f %.2f", a, b, c, d);
perimeter = a + b + c + d;
System.out.printf("\nThe perimeter of Rectangle is: %.2f", perimeter);
}
}
โค้ดที่กระชับกว่า
float length = 5, width = 8;
float perimeter = 2 * (length + width);
System.out.println("Perimeter: " + perimeter);
สูตร 2×(length+width) เข้าใจง่ายและคำนวณเร็วกว่า