求三角形面積

編寫程序,提示用戶輸入三角形的三個點(x1,y1),(x2,y2),(x3,y3),然後顯示它的面積。
計算公式:
s = (邊1+邊2+邊3)/2
面積=√s(s-s1)(s-s2)(s-s3)

使用java中的Scanner類從鍵盤輸入座標值
創建Scanner對象的基本語法:

Scanner scanner = new Scanner(System.in);

使用next()方法獲取三個點座標

  double y1 = scanner.nextDouble();
  double x2 = scanner.nextDouble();
  double y2 = scanner.nextDouble();
  double x3 = scanner.nextDouble();
  double y3 = scanner.nextDouble();

再使用Math.sqrt()和Math.pow()函數 用座標點計算出三角形邊長,最後代入公式就可以求出三角形面積。

完整代碼如下:

package Test;
import java.util.Scanner;
public class Exercise01 {
 public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  System.out.print("Enter three points for a triangle:");
  double x1 = scanner.nextDouble();
  double y1 = scanner.nextDouble();
  double x2 = scanner.nextDouble();
  double y2 = scanner.nextDouble();
  double x3 = scanner.nextDouble();
  double y3 = scanner.nextDouble();
  double s1 = Math.sqrt(Math.pow((x1-x2),2)+Math.pow((y1-y2),2));
  double s2 = Math.sqrt(Math.pow((x1-x3),2)+Math.pow((y1-y3),2));
  double s3 = Math.sqrt(Math.pow((x2-x3),2)+Math.pow((y2-y3),2));
  double s = (s1+s2+s3)/2;
  double area = Math.sqrt(s*(s-s1)*(s-s2)*(s-s3));
  System.out.println("The area of the triangle is "+area);
 }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章