2013-02-03 91 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; 
相關問題