我有一个获取三角形区域的方法,但它返回0.0。
public double getArea() {
//Find the length of sides
double side1 = p1.findLength(p2);
double side2 = p2.findLength(p3);
double side3 = p3.findLength(p1);
//Get area
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
我的Point类与findLength()。此功能在我的测试中起作用:
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
我似乎无法弄清楚它为什么不起作用。
整点类:
/**
* Created by wilson on 9/8/2014.
*/
import java.math.*;
public class Point {
private double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double findLength(Point another) {
return Math.sqrt(((another.getX() - this.getX()) * (another.getX() - this.getX()) )+
((another.getY() - this.getY()) * (another.getY() - this.getY())));
}
}
我的考试计划:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
Triangle2D t1 = new Triangle2D(p1, p2, p3);
System.out.println("Area of triangle: " + t1.getArea());
答案 0 :(得分:0)
"三角形"你测试过:
Point p1 = new Point(0,0);
Point p2 = new Point(3,3);
Point p3 = new Point(-3,-3);
实际上由三个点组成在同一条线上(线 x = y )。因此,0是正确的答案。据我所知,代码是正确的。
附注:我建议使用Math.hypot
,它在findLength
函数中计算sqrt(x 2 + y 2 )。除了使findLength
更容易阅读之外,如果x或y大到x 2 或y 2 ,它的优势在于它不会溢出不符合浮点数。 (并不是说你可能会遇到这个问题,但为什么不做正确的事呢?)