给定点数,顺时针输入点位坐标,计算不规则多边形周长!
点击链接下载源代码
ackage information; public class Point { public float x; public float y; public Point next; // 坐标的下一个结点 public Point(float x, float y) { this.x = x; this.y = y; } @Override public String toString() { // TODO Auto-generated method stub String str = ""; int i = 1; for (Point p = this; p != null; p = p.next) { str += "第" + i + "个坐标:(" + p.x + "," + p.y + ")\n"; i++; } return str; } } package information; import java.util.Scanner; //按照顺时针依次输入多边形顶点坐标,计算面积和周长 public class Polygon { // 建立多边形的点的链表,输入时按照顺时针顺序输入点的坐标 public Point initial() { @SuppressWarnings("unused") Point tmp = null, head = null; System.out.println("请按顺时针顺序输入多边形的坐标点数:"); @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int n = sc.nextInt(); if (n < 3) { System.out.println("多边形点数过3!");; } for (int i = 0; i < n; i++) { System.out.println("请输入第" + (i + 1) + "个坐标的x坐标:"); float x = sc.nextFloat(); System.out.println("请输入第" + (i + 1) + "个坐标的y坐标:"); float y = sc.nextFloat(); Point p = new Point(x, y); if (head == null) { head = p; head.next = null; } else { p.next = head; head = p; } } return head; } /** * 计算多边形周长 * * @param head * @return */ public float computeCircumference(Point head) { float result = 0; for (Point u = head, v = head.next; v != null; u = u.next, v = v.next) { float m = u.x - v.x; float n = u.y - v.y; result += Math.sqrt(m * m + n * n); } for (Point u = head, v = u; v != null; v = v.next) { if (v.next == null) { float m = u.x - v.x; float n = u.y - v.y; result += Math.sqrt(m * m + n * n); } } return result; } } package information; public class Test { public static void main(String[] args) { Polygon p = new Polygon(); Point head = p.initial(); System.out.println(head.toString()); Float circumference = p.computeCircumference(head); System.out.println("周长:" + circumference); } }