计算不规则多边形周长|8月更文挑战

511 阅读1分钟

这是我参与8月更文挑战的第8天,活动详情查看:8月更文挑战

在给定点数的状态下,顺时针输入点位坐标,计算不规则多边形周长! 这个图形是非常不规则的,那么如果我们直接这样去计算它的周长,恐怕是非常困难的。不过把这个图形一些部位进行平移,我们会惊奇地发现这个图形是非常完整的!

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);
	}
}