Java中多边形周长的计算
我有一个名为permiture的方法,它应该接受一些点,并根据提供的点返回多边形的周长。当我使用测试仪运行程序时,我总是得到错误的周长答案Java中多边形周长的计算,java,arraylist,geometry,Java,Arraylist,Geometry,我有一个名为permiture的方法,它应该接受一些点,并根据提供的点返回多边形的周长。当我使用测试仪运行程序时,我总是得到错误的周长答案 import java.util.ArrayList; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; /**A class that represents a geometric polygon. Methods are provided for adding *
import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
/**A class that represents a geometric polygon. Methods are provided for adding
* a point to the polygon and for calculating the perimeter and area of the
* polygon.
*/
class MyPolygon {
//list of the points of the polygon
private ArrayList<Point2D.Double> points;
/**Constructs a polygon with no points in it.
*/
public MyPolygon() {
points = new ArrayList<Point2D.Double>();
}
/**Adds a point to the end of the list of points in the polygon.
* @param x The x coordinate of the point.
* @param y The y coordinate of the point.
*/
public void add(double x, double y) {
points.add(new Point2D.Double(x,y));
}
/**Calculates and returns the perimeter of the polygon.
* @return 0.0 if < 2 points in polygon, otherwise returns the
* sum of the lengths of the line segments.
*/
public double perimeter() {
if (points.size() < 2){
return 0.0;
}
int i = 0;
double d = 0;
double total = 0;
while (i < points.size() - 1 )
{
Point2D.Double point1 = points.get(i);
double x = point1.x;
double y = point1.y;
Point2D.Double point2 = points.get(i+1);
double x1 = point2.x;
double y1 = point2.y;
d = point1.distance(point2);
System.out.println(d);
//d = Math.sqrt(Math.pow(x1 - x,2) + Math.pow(y1 - y, 2));
total = total + d;
i++;
}
return total;
}
/**Calculates and returns the area of the polygon.
* @return 0.0 if < 3 points in the polygon, otherwise returns
* the area of the polygon.
*/
public double area() {
return 0;
}
}
应使用最后一条边的长度初始化total变量:
double total = points.get(0).distance(poinsts.get(points.size() - 1));
你得到的错误答案是什么?你期望它是什么?你忘了回到起点的边了吗?我应该得到6.82842712474619你说的回到起点的边是什么意思?从最后一点回到第一点的边。你没有把最后的优势加到你的总数上。
double total = points.get(0).distance(poinsts.get(points.size() - 1));