calculate area of triangle given 3 user defined points -Beginner

陌路散爱 提交于 2019-12-10 15:28:49

问题


I can get my code to compile, but it doesn't produce the area that is desired. I'm not sure where I have stumbled.

They want you to have the user enter 6 coordinates (x and y value) for the 3 points of a triangle and get the area. My code is as follows:

import java.util.Scanner;

public class AreaTriangle {
    // find the area of a triangle
    public static void main (String [] args) {
        double side1 = 0;
        double side2 = 0;
        double side3 = 0;

        Scanner input = new Scanner(System.in);

        //obtain three points for a triangle
        System.out.print("Enter three points for a triangle (x and y intercept): ");
        double side1x  = input.nextDouble();
        double side1y  = input.nextDouble();
        double side2x  = input.nextDouble();
        double side2y  = input.nextDouble();
        double side3x  = input.nextDouble();
        double side3y  = input.nextDouble();

        //find length of sides of triangle
        side1 = Math.pow(Math.pow((side2x - side1x), 2) + Math.pow((side2y - side1y), 2) * .05, side1);
        side2 = Math.pow(Math.pow((side3x - side2x), 2) + Math.pow((side3y - side2y), 2) * .05, side2);
        side3 = Math.pow(Math.pow((side1x - side3x), 2) + Math.pow((side1y - side3y), 2) * .05, side3);

        double s = (side1 + side2 + side3) / 2;

        double area = Math.sqrt(s * (s - side1) * (s - side2) * (s-side3)) * 0.5;

        System.out.println("area" + area);
    }
}

回答1:


You should try implementing this equation. http://www.mathopenref.com/coordtrianglearea.html




回答2:


@Michael's suggestion is a good one. Following your code, I'd use Pythagoras' Theorem like this:

side1 = Math.sqrt(
            Math.pow((side2x - side1x), 2)
          + Math.pow((side2y - side1y), 2));

In your code:

side1 = Math.pow(
            Math.pow((side2x - side1x), 2) 
          + Math.pow((side2y - side1y), 2) * .05
       , side1);

side1 is 0 before the calculation, and almost anything to the power 0 is 1. Therefore side1 ends as 1 regardless of the points.




回答3:


Another way I've discovered is that you can use the cross product to find the area of a triangle. This may be slightly easier for you, since you already have the points. You can turn the three points in to two vectors and take the cross product.

edit: Whoops, forgot to add in the area of a triangle would be half of the cross product, since the cross product would give you the area of a parallelogram formed by the two vectors (and a triangle is half that).



来源:https://stackoverflow.com/questions/14573785/calculate-area-of-triangle-given-3-user-defined-points-beginner

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!