โปรแกรมหาพื้นที่สามเหลี่ยม สี่เหลี่ยม

วันนี้เรามาเขียนโปรแกรม หาพื้นที่สามเหลี่ยม กับ สี่เหลี่ยมกัน เรามาดูโปรแกรมแรกกัน เป็น

โปรแกรมหาพื้นที่สี่เหลี่ยมมุมฉาก

 import java.util.Scanner; public class Main {     public static void main(String[] args ) {         Scanner in = new Scanner(System.in);         System.out.print("Input width : ");         double width = in.nextDouble();         System.out.print("Input length : ");         double length = in.nextDouble();         System.out.println("-----------------------");         System.out.println("square area : " + width * length);     } }

ผลการรันโปรแกรม

Input width : 7 
Input length : 9 
-----------------------
square area : 63.0

ขั้นแรกเราก็ทำการสร้างอ็อบเจ็ค เพื่อทำการรับความกว้าง กับความสูง ของสี่เหลี่ยมมุมฉาก ต่อมาก็ทำการรับค่าความสงกับความกว้าง ก่อนที่จะรับค่าก็ทำการแสดงให้ผู้กรอกทราบว่าต้องกรอกอะไร ต่อมาก็ปริ้นสรุป และนำความกว้างกับความสูงมาคูณกัน จาก "square area : " + width * height เนื่องจากการคูณจะทำการดำเนินการก่อนการบวก เราไม่จำเป็นต้องใส่วงเล็บก็ได้


โปรแกรมต่อไป เป็น

โปรแกรมหาพื้นที่สามเหลี่ยม

 import java.util.Scanner; public class Main {     public static void main(String[] args ) {         Scanner in = new Scanner(System.in);         System.out.print("Input width : ");         double width = in.nextDouble();         System.out.print("Input height : ");         double height = in.nextDouble();         System.out.println("-----------------------");         System.out.println("The triangular area : " + 0.5 * width * height);     } }

ผลการรันโปรแกรม

Input width : 8
Input height : 5
-----------------------
The triangular area : 20.0

โปรแกรมนี้ต่างกับโปรแกรมแรกแค่เพิ่ม 0.5 คูณเข้าไปตรงที่คำนวณเท่านั้น