我正在尝试编写Java代码,该代码获取三角形的顶点(这将是用户输入)并输出所述三角形的面积。我得到NaN
作为回应。我应该把我的类型改成float吗?我是不是要走更长的路来解决这个问题?
使用的公式有Distance公式和Heron公式。
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);
}
}
问题是计算错误。
从(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)
。)
我建议您使用更简单的分析公式
|(X2 - X0) (Y1 - Y0) - (X1 - X0) (Y2 - Y0)| / 2
不取绝对值,符号告诉你三角形是顺时针还是逆时针。