c#设计程序创建点类用点的坐标求三角形面积和周长
1个回答
展开全部
//点类Point
class Point
{
private double x, y;
// 构造函数
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public double X { get { return x; } }
public double Y { get { return y; } }
// 获取两个点之间的距离
public static double Distance(Point p1, Point p2)
{
return Math.Sqrt(
(p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.Y) * (p1.y - p2.Y));
}
}
//三角形类Triangle
class Triangle
{
private Point p1, p2, p3;
// 构造函数
public Triangle(Point p1, Point p2, Point p3)
{
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
// 获取三角形面积
public double GetArea()
{
double d1 = Point.Distance(p1, p2);
double d2 = Point.Distance(p2, p3);
double d3 = Point.Distance(p3, p1);
double s = (d1 + d2 + d3) / 2;
return Math.Sqrt(s * (s - d1) * (s - d2) * (s - d3));
}
// 获取三角形周长
public double GetPerimeter()
{
double d1 = Point.Distance(p1, p2);
double d2 = Point.Distance(p2, p3);
double d3 = Point.Distance(p3, p1);
return d1 + d2 + d3;
}
}
// 测试上面定义的类
class Program
{
static void Main(string[] args)
{
// 三个点
Point p1 = new Point(-1, 0);
Point p2 = new Point(0, 1);
Point p3 = new Point(1, 0);
// 由三个点构成的三角形
Triangle t = new Triangle(p1, p2, p3);
double area = t.GetArea();
Console.WriteLine("面积为:{0}", area);
double perimeter = t.GetPerimeter();
Console.WriteLine("周长为:{0}", perimeter);
Console.ReadLine();
}
}
注意:简化起见,在Triangle中没有判断三个点是否在同一条直线上!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询