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

โปรแกรม Java คำนวณปริมาตรทรงสี่หน้า (Tetrahedron)

ทรงสี่หน้า (Tetrahedron) คืออะไร?

Tetrahedron เป็นทรงหลายหน้า (Polyhedron) ที่มี 4 หน้าเป็นรูปสามเหลี่ยม 6 棱 (Edges) และ 4 จุดยอด (Vertices) เป็นทรงพลัตออนิก (Platonic Solid) ที่เรียบง่ายที่สุด

สูตรปริมาตร

สำหรับ Regular Tetrahedron (ทรงสี่หน้าปกติ - ทุกหน้าเป็นสามเหลี่ยมด้านเท่า ด้านยาว a):

V = a³ / (6√2) ≈ 0.11785 × a³

ตัวอย่างโค้ด

import java.io.*; 

public class Demo { 
    static double tetraVolume(int side) { 
        // V = a³ / (6√2)
        double volume = (Math.pow(side, 3)) / (6 * Math.sqrt(2)); 
        return volume; 
    } 
    
    public static void main(String[] args) { 
        int side = 4; 
        double volume = tetraVolume(side); 
        
        // ปัดเศษ 2 ตำแหน่งทศนิยม
        volume = Math.round(volume * 100.0) / 100.0; 
        
        System.out.println("ปริมาตรทรงสี่หน้า (ด้าน = " + side + "): " + volume); 
    } 
}

ผลลัพธ์

ปริมาตรทรงสี่หน้า (ด้าน = 4): 7.54

คำอธิบาย

  • เมธอด tetraVolume รับความยาวด้าน คำนวณตามสูตร คืนค่า double
  • Math.pow(side, 3) คำนวณ a³
  • Math.sqrt(2) รากที่สองของ 2
  • Math.round(x * 100) / 100.0 ปัดเศษ 2 ตำแหน่งทศนิยม

ข้อสังเกต: โค้ดต้นฉบับเขียน "Area" แต่คำนวณ "Volume"

โค้ดต้นฉบับพิมพ์ "The area of tetrahedron is" แต่คำนวณเป็นปริมาตร (Volume) ไม่ใช่พื้นที่ผิว (Surface Area)

สูตรเพิ่มเติม

  • Surface Area = √3 × a² ≈ 1.732 × a²
  • Height = √(2/3) × a ≈ 0.816 × a

ตัวอย่างเพิ่มเติม: รับค่าจากผู้ใช้

import java.util.Scanner; 

public class TetraCalculator { 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.print("กรอกความยาวด้าน: "); 
        double side = sc.nextDouble(); 
        
        double volume = Math.pow(side, 3) / (6 * Math.sqrt(2)); 
        double surfaceArea = Math.sqrt(3) * side * side; 
        
        System.out.printf("ปริมาตร: %.4f%n", volume); 
        System.out.printf("พื้นที่ผิว: %.4f%n", surfaceArea); 
    } 
}