用c#编写一个求取包络线面积的程序
时间: 2023-10-10 22:10:16 浏览: 75
以下是一个用 C# 编写的求取包络线面积的程序示例:
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnvelopeArea
{
class Program
{
static void Main(string[] args)
{
// 输入多边形点坐标
List<Point> points = new List<Point>();
Console.WriteLine("请输入多边形点坐标,输入 end 结束输入:");
string input = Console.ReadLine();
while (input != "end")
{
string[] values = input.Split(',');
double x = double.Parse(values[0]);
double y = double.Parse(values[1]);
Point point = new Point(x, y);
points.Add(point);
input = Console.ReadLine();
}
// 计算包络线面积
double area = CalculateEnvelopeArea(points);
Console.WriteLine("包络线面积为:" + area);
Console.ReadKey();
}
// 定义点类
class Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
}
// 计算两点之间的距离
static double Distance(Point p1, Point p2)
{
double dx = p2.X - p1.X;
double dy = p2.Y - p1.Y;
return Math.Sqrt(dx * dx + dy * dy);
}
// 计算三角形面积
static double TriangleArea(Point p1, Point p2, Point p3)
{
double a = Distance(p1, p2);
double b = Distance(p2, p3);
double c = Distance(p3, p1);
double p = (a + b + c) / 2;
return Math.Sqrt(p * (p - a) * (p - b) * (p - c));
}
// 计算包络线面积
static double CalculateEnvelopeArea(List<Point> points)
{
// 找到最左边和最右边的点
Point leftMost = points.OrderBy(p => p.X).First();
Point rightMost = points.OrderBy(p => p.X).Last();
// 分别计算左边和右边的包络线
List<Point> leftEnvelope = new List<Point>();
List<Point> rightEnvelope = new List<Point>();
Point current = leftMost;
while (current != rightMost)
{
leftEnvelope.Add(current);
current = points.Where(p => p.X < current.X && !leftEnvelope.Contains(p))
.OrderByDescending(p => Distance(current, p))
.First();
}
leftEnvelope.Add(rightMost);
current = rightMost;
while (current != leftMost)
{
rightEnvelope.Add(current);
current = points.Where(p => p.X > current.X && !rightEnvelope.Contains(p))
.OrderByDescending(p => Distance(current, p))
.First();
}
rightEnvelope.Add(leftMost);
// 合并左右包络线
List<Point> envelope = leftEnvelope.Concat(rightEnvelope.Skip(1)).ToList();
// 计算包络线面积
double area = 0;
for (int i = 1; i < envelope.Count - 1; i++)
{
area += TriangleArea(envelope[0], envelope[i], envelope[i + 1]);
}
return area;
}
}
}
```
在程序中,首先输入多边形各个点的坐标,输入 "end" 结束输入。然后通过 CalculateEnvelopeArea 方法计算多边形的包络线面积。CalculateEnvelopeArea 方法首先找到最左边和最右边的点,然后分别计算左边和右边的包络线,最后合并左右包络线并计算包络线面积。其中,Distance 方法用于计算两点之间的距离,TriangleArea 方法用于计算三角形面积。
阅读全文