我试图编写采用三角形顶点(将是用户输入)的Java代码并输出所述三角形的区域。我得到NaN
作为回复。我应该将我的类型改成浮动吗?我是否采取了更长的路线尝试解决这个问题?
使用的公式是距离公式和苍鹭公式。
import java.util.Scanner;
public class TriangleArea {
public static void main(String[]args){
Scanner user = new Scanner(System.in);
System.out.println("To compute the area of a triangle, please input a point in a vertex when prompted");
System.out.println("Please input X of the first vertex: x ");
double firstVertexX = user.nextDouble();
System.out.println("Please input Y of the first vertex: y ");
double firstVertexY = user.nextDouble();
System.out.println("Please input X of the second vertex: x");
double secondVertexX = user.nextDouble();
System.out.println("Please input Y of the second vertex: y ");
double secondVertexY = user.nextDouble();
System.out.println("Please input X of the third vertex: x");
double thirdVertexX = user.nextDouble();
System.out.println("Please input Y of the third vertex: y");
double thirdVertexY = user.nextDouble();
double sideOneX = Math.pow(firstVertexX * 1, 2) - Math.pow(secondVertexX * 2, 2);
double sideOneY = Math.pow(firstVertexY * 1, 2) - Math.pow(secondVertexY * 2, 2);
double sideOne = Math.pow(sideOneX + sideOneY, .5);
double sideTwoX = Math.pow(secondVertexX * 1, 2) - Math.pow(thirdVertexX * 2, 2);
double sideTwoY = Math.pow(secondVertexY * 1, 2) - Math.pow(thirdVertexY * 2, 2);
double sideTwo = Math.pow(sideTwoX + sideTwoY, .5);
double sideThreeX = Math.pow(thirdVertexX * 1, 2) - Math.pow(firstVertexX * 2, 2);
double sideThreeY = Math.pow(thirdVertexY * 1, 2) - Math.pow(firstVertexY * 2, 2);
double sideThree = Math.pow(sideThreeX + sideThreeY, .5);
double s = (sideOne + sideTwo + sideThree)/2;
double areaStepOne = (s - sideOne) * (s - sideTwo) * (s - sideThree);
double areaStepTwo = s * areaStepOne;
double area = Math.pow(areaStepTwo, .5);
System.out.println("The area of the triangle is " + area + ".");
System.out.println("The area of the triangle is " + area);
}
}
答案 0 :(得分:1)
这个问题是错误的估计。
从(x1,y1)到(x2,y2)的线段长度为sqrt((x1-x2)^ 2 +(y1-y2)^ 2)。
你要计算的是:sqrt(x1 ^ 2 - (x2 * 2)^ 2 + y1 ^ 2 - (y2 * 2)^ 2)。这可能是消极的,给你NaN。
我将这些行更改为:
double sideOneX = firstVertexX - secondVertexX;
double sideOneY = firstVertexY - secondVertexY;
double sideOne = Math.sqrt(sideOneX * sideOneX + sideOneY * sideOneY);
(您可以使用Math.sqrt(v)
代替Math.pow(v, .5)
。)
答案 1 :(得分:1)
我建议你使用更简单的分析公式
|(X2 - X0) (Y1 - Y0) - (X1 - X0) (Y2 - Y0)| / 2
没有取绝对值,符号会告诉您三角形是顺时针还是逆时针。