Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a program that calculates the perimeter and the area of given polygon (not necessarily convex) consisting of n floating-point coordinates in the 2D plane. Print the result rounded to two decimal digits after the decimal point. Use the input and output format from the examples. To hold the points, define a class Point(x, y). To hold the polygon use a Polygon class which holds a list of points.
- namespace _17.PerimeterAndAreaOfPolygon
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- public class Point
- {
- public Point(double x, double y)
- {
- this.X = x;
- this.Y = y;
- }
- public double X { get; set; }
- public double Y { get; set; }
- public double Distance(Point p2)
- {
- double x1 = this.X;
- double y1 = this.Y;
- double x2 = p2.X;
- double y2 = p2.Y;
- double distance = Math.Sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
- return distance;
- }
- }
- public class Polygon
- {
- private List<Point> pointList;
- public Polygon()
- {
- this.pointList = new List<Point>();
- }
- public Polygon(List<Point> pointList)
- {
- this.pointList = new List<Point>(pointList);
- }
- public double Area()
- {
- double left = 0;
- double right = 0;
- for (int i = 0; i < this.pointList.Count - 1; i++)
- {
- Point p1 = this.pointList[i];
- Point p2 = this.pointList[i + 1];
- left += p1.X * p2.Y;
- right += p2.X * p1.Y;
- }
- double area = Math.Abs(left - right) / 2;
- return area;
- }
- public double Perimeter()
- {
- this.pointList.Add(this.pointList[0]);
- double perimeter = 0;
- for (int i = 0; i < this.pointList.Count - 1; i++)
- {
- Point p1 = this.pointList[i];
- Point p2 = this.pointList[i + 1];
- perimeter += p1.Distance(p2);
- }
- return perimeter;
- }
- }
- public class PerimeterAndAreaOfPolygon
- {
- public static void Main(string[] args)
- {
- checked
- {
- int countPoints;
- do
- {
- Console.Write("Enter Integer number, bigger from 2, for Count of Polygon points: ");
- }
- while (!int.TryParse(Console.ReadLine(), out countPoints) || countPoints < 3);
- List<Point> pointList = new List<Point>();
- Console.WriteLine("Entries your coordinates, each point by line, exactly this format [x y]!");
- for (int i = 0; i < countPoints; i++)
- {
- string inputLine = Console.ReadLine();
- char[] separators = { ' ', ',', ';' };
- string[] coordinates = inputLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);
- double x = double.Parse(coordinates[0]);
- double y = double.Parse(coordinates[1]);
- Point p = new Point(x, y);
- pointList.Add(p);
- }
- Polygon polygon = new Polygon(pointList);
- double area = polygon.Area();
- double perimeter = polygon.Perimeter();
- Console.WriteLine("The Perimeter of that Polygon is {0:f2} !", perimeter);
- Console.WriteLine("The Area of that Polygon is {0:f2} !", area);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement