Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java หาเส้นรอบวงวงกลม (Perimeter/Circumference of Circle)


ในบทความนี้ เราจะทำความเข้าใจวิธี หาเส้นรอบวง (Circumference/Perimeter) ของวงกลม

สูตร: C = 2πr โดย π ≈ 22/7 หรือ 3.14, r = รัศมี

ตัวอย่าง Input และ Output

Input:

Radius of the circle : 5

Output:

Perimeter of Circle is: 31.428571428571427

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร double my_radius, my_perimeter
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - คำนวณเส้นรอบวง = (2 * 22 * my_radius) / 7
ขั้นตอนที่ 5 - แสดงผลลัพธ์
ขั้นตอนที่ 6 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class PerimeterOfCircle {
    public static void main(String args[]) {
        double my_radius, my_perimeter;
        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 radius of the circle : ");
        my_radius = my_scanner.nextDouble();
        my_perimeter = (22 * 2 * my_radius) / 7;
        System.out.println("The perimeter of Circle is: " + my_perimeter);
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the radius of the circle : 5
The perimeter of Circle is: 31.428571428571427

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class PerimeterOfCircle {
    public static void main(String args[]) {
        double my_radius, my_perimeter;
        my_radius = 5;
        System.out.println("The radius of the circle is defined as " + my_radius);
        my_perimeter = (22 * 2 * my_radius) / 7;
        System.out.println("The perimeter of Circle is: " + my_perimeter);
    }
}

Output

The radius of the circle is defined as 5.0
The perimeter of Circle is: 31.428571428571427