gpt4 book ai didi

java - 用Java计算多边形的周长

转载 作者:行者123 更新时间:2023-12-01 13:23:51 25 4
gpt4 key购买 nike

我有一个称为周长的方法,它应该接受一些点并根据提供的点返回多边形的周长。当我使用测试仪运行程序时,我总是得到错误的周长答案。

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;

}

}

测试器类:

class PolygonTester {

public static void main(String args[]) {
MyPolygon poly = new MyPolygon();
poly.add(1.0,1.0);
poly.add(3.0,1.0);
poly.add(1.0,3.0);
System.out.println(poly.perimeter());
System.out.println(poly.area());
}

}

最佳答案

您应该使用最后一条边的长度来初始化总变量:

double total = points.get(0).distance(poinsts.get(points.size() - 1));

关于java - 用Java计算多边形的周长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21892177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com