ในบทความนี้ เราจะเรียนรู้วิธีคำนวณพื้นที่วงกลมในภาษา Java
สูตร
Area = π × r²
โดย π ≈ 3.14 หรือ 22/7, r = รัศมี
ตัวอย่างการทำงาน
อินพุต:
Radius of the circle: 5
เอาต์พุต:
The Area of Circle is: 78.57142857142857
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร double:
area,radius - รับค่ารัศมีจากผู้ใช้
- คำนวณพื้นที่:
area = (22 * radius * radius) / 7 - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String args[]) {
double area, radius;
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.println("Enter the radius of the circle:");
radius = my_scanner.nextDouble();
area = (22 * radius * radius) / 7;
System.out.println("The Area of Circle is: " + area);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class AreaOfCircle {
public static void main(String args[]) {
double radius = 5, area;
System.out.printf("The radius of the circle is %.8f ", radius);
area = (22 * radius * radius) / 7;
System.out.println("\nThe Area of Circle is: " + area);
}
}
วิธีที่แม่นยำกว่า: ใช้ Math.PI
double area = Math.PI * radius * radius;
// หรือ
double area = Math.PI * Math.pow(radius, 2);
Math.PI ให้ค่า π แม่นยำกว่า 22/7 (3.141592653589793) ควรใช้ในการคำนวณจริง