2013-02-03 52 views
5

我一直在这个小时,尝试不同的方法来看待每个问题。也许我完全错了,但我觉得我的数学是正确的,但无论输入什么数字,我都会得到相同的输出。我的代码已关闭,我必须在午夜之前将其关闭。寻找一个点是否在一个三角形内

这是非常有趣的:找到一个点是否在三角形代码内。 (初学者)

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 
+0

这可能是值得输出你认为你作为调试的一部分读值... – Floris

回答

5

如果绘制一个图象,可以看到点必须满足简单不等式(低于/高于/某些线的右边)。无论是“在边缘”是或缩小,我会离开给你:

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

写的,如果这三个周围声明,你就大功告成了:

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"); 
+0

我不能感谢你才好。我一直都在反思一切。你已经度过了我的周末! – Lish

+0

@Lish - 不客气。深夜会对你的大脑产生影响...... – Floris

5

你放在了错误的价值秩序进入你的公式;因此,结果是错误的。如果3个顶点是因为以下

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

那么面积作为

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

在此之后,你只用输入点替换每个顶点,我们将有以下三角形:中国人民银行, 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; 
相关问题