计算三角形的面积

时间:2015-05-27 03:23:06

标签: java

我是Java新手。我正在尝试使用以下公式计算三角形的面积:

s =(第1侧+第2侧+第3侧)/ 2

面积=平方根(侧面(侧面1)(侧面 - 侧面2)(侧面 - 侧面3)。

如果用户输入以下三点: 1.5 -3.4 4.6 5 9.5 -3.4然后三角形的面积应为33.6。但是,我的程序运行,但它给了我一个错误的答案。以下是我的代码。

// Import Java Scanner
import java.util.Scanner;
import java.lang.Math;
public class Ex_2_19 {
    public static void main(String[] args) {
    //Create a Scanner object
    Scanner input = new Scanner(System.in);
    float side = 0;
    float area1 = 0;
    float area2 = 0;
    float area3 = 0;
    float area4 = 0;
    float calculatedarea = 0;

    //Prompt the user to enter three points of a triangle
    System.out.println("Enter point x1:");
    System.out.println("Enter point y1:");
    System.out.println("Enter point x2:");
    System.out.println("Enter point y2:");
    System.out.println("Enter point x3:");
    System.out.println("Enter point y3:");

    //Define the variables
    float Pointx1 = input.nextFloat();
    float Pointy1 = input.nextFloat();
    float Pointx2 = input.nextFloat();
    float Pointy2 = input.nextFloat();
    float Pointx3 = input.nextFloat();
    float Pointy3 = input.nextFloat();

    //Formula to calculate the area of a triangle
    side = (Pointx1 + Pointy1 + Pointx2 + Pointy2 + Pointx3 + Pointy3) / 2;
    area1 = side - (Pointx1 + Pointy1);
    area2 = side - (Pointx2 + Pointy2);
    area3 = side - (Pointx3 + Pointy3);
    area4 = side * area1 * (area2) * (area3);
    calculatedarea = (float) (Math.sqrt(area4)); 
    //calculatedarea = (float) (Math.sqrt(area1)*(area2) * (area3)); 

    //Print result
    System.out.println("The area of the triangle is " + calculatedarea);


}

}

1 个答案:

答案 0 :(得分:4)

您正在尝试Heron's Formula - 请注意,abc是各点之间的欧氏距离,因此需要由sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))等计算,而不仅仅是差异的总和。