【问题标题】:Finding whether a point is within a triangle判断一个点是否在三角形内
【发布时间】:2016-03-15 20:19:20
【问题描述】:

我已经研究了好几个小时,尝试了不同的方法来查看几乎每个问题。也许我完全错了,但我觉得我的数学是正确的,但无论我输入什么数字,我都会得到相同的输出。我的代码在某处关闭,我必须在午夜前将其上交。

太有趣了:查找一个点是否在三角形代码内。 (适合初学者)

import java.util.Scanner;

public class PointsTriangle {

    // checks if point entered is within the triangle
    //given points of triangle are (0,0) (0,100) (200,0)
    public static void main (String [] args) {
        //obtain point (x,y) from user
        System.out.print("Enter a point's x- and y-coordinates: ");
        Scanner input = new Scanner(System.in);
        double x = input.nextDouble();
        double y = input.nextDouble();

        //find area of triangle with given points
        double ABC = ((0*(100-0  )+0*(0  -0)+200*(0-100))/2.0);
        double PAB = ((x*(0  -100)+0*(100-y)+0  *(y-  0))/2.0);
        double PBC = ((x*(100-0  )+0*(0  -y)+200*(y-100))/2.0);
        double PAC = ((x*(0  -100)+0*(100-y)+200*(y-  0))/2.0);

        boolean isInTriangle = PAB + PBC + PAC == ABC;

        if (isInTriangle)
            System.out.println("The point is in the triangle");
        else
            System.out.println("The point is not in the triangle");
    }//end main
}//end PointsTriangle

【问题讨论】:

  • 作为调试的一部分输出你认为你读到的值可能是值得的......

标签: java geometry


【解决方案1】:

您在公式中放置了错误的值顺序;因此,结果是错误的。如果3个顶点如下

A(x1, y1) B(x2, y2), C(x3, y3)

那么面积计算为

double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2;

之后,您只需将每个顶点替换为输入点,我们将有以下三角形:PBC、APC、ABP。

把所有东西放在一起,我们会得到正确的

int x1 = 0, y1 = 0;
int x2 = 0, y2 = 100;
int x3 = 200, y3 = 0;

// no need to divide by 2.0 here, since it is not necessary in the equation
double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
double ABP = Math.abs (x1 * (y2 - y) + x2 * (y - y1) + x * (y1 - y2));
double APC = Math.abs (x1 * (y - y3) + x * (y3 - y1) + x3 * (y1 - y));
double PBC = Math.abs (x * (y2 - y3) + x2 * (y3 - y) + x3 * (y - y2));

boolean isInTriangle = ABP + APC + PBC == ABC;

【讨论】:

    【解决方案2】:

    如果你画一张图,你可以看到这个点必须满足简单的不等式(在某些线的下方/上方/右侧)。 “边缘”是进还是出,我将由您决定:

    Y > 0 (above the X axis)
    X > 0 (to the right of the Y axis)
    X + 2* Y < 200 (below the hypotenuse)
    

    围绕这三个写一个 if 语句,你就完成了:

    if( (y > 0) && (x > 0) && (x + 2*y < 200) ) 
      System.out.println("The point is in the triangle");
    else
      System.out.println("The point is not in the triangle");
    

    【讨论】:

    • 我对你感激不尽。我总是想太多。你让我度过了一个周末!
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 2011-10-30
    • 2017-02-01
    • 2013-04-24
    相关资源
    最近更新 更多