2013-02-03 9 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

あなたが絵を描く場合は、ポイントは(特定の行の右/以上/以下に)簡単な不平等を満たすために持って見ることができます。これら三つの周りにif文

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

書き込みANを、あなたが行われている:

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

あなたは間違った値の順序を置いた「エッジ上」かどうかは、私はあなたにお任せします、あるいは出ていますあなたの数式に入れる。したがって、結果は間違っています。 、PBC: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; 
関連する問題