今日は将棋から離れた内容を投稿します。
気分転換ですね。
ということで三角形の面積を求めてみました。
実行結果
import java.util.Scanner;
import java.awt.geom.Point2D;
class Test01{
public static void main(String[] args){
Point2D.Double a=new Point2D.Double();
Point2D.Double b=new Point2D.Double();
Point2D.Double c=new Point2D.Double();
Scanner s=new Scanner(System.in);
System.out.print("a.x: "); a.x=s.nextDouble();
System.out.print("a.y: "); a.y=s.nextDouble();
System.out.print("b.x: "); b.x=s.nextDouble();
System.out.print("b.y: "); b.y=s.nextDouble();
System.out.print("c.x: "); c.x=s.nextDouble();
System.out.print("c.y: "); c.y=s.nextDouble();
System.out.println("三角形の面積:"+triangleArea(a,b,c));
}
public static double triangleArea(Point2D.Double a,Point2D.Double b,Point2D.Double c){
return Math.abs((a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y))/2;
}
}
/* 実行結果
a.x: 0
a.y: 0
b.x: 1
b.y: 0
c.x: 1
c.y: 1
三角形の面積:0.5
a.x: -1
a.y: 1
b.x: 0
b.y: 0
c.x: 1
c.y: 1
三角形の面積:1.0
*/
普通のPoint型はそれぞれint型なので、うまくいきませんでした。
Point2D.Doubleを使ったところうまくいったので注意してください。
java.awt.geom.Point2Dをインポートしてください。
コメント