Python实现平面几何图形:点、线段、三角形
以下是Python实现:
import math
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
class Line:
def __init__(self, p1 = Point(), p2 = Point()):
self.p1 = p1
self.p2 = p2
class Triangle:
def __init__(self, l1 = Line(), l2 = Line(), l3 = Line()):
self.l1 = l1
self.l2 = l2
self.l3 = l3
# 复制构造函数
def __init__(self, t):
self.l1 = Line(t.l1.p1, t.l1.p2)
self.l2 = Line(t.l2.p1, t.l2.p2)
self.l3 = Line(t.l3.p1, t.l3.p2)
# 判断是否构成三角形
def is_triangle(self):
d1 = math.sqrt((self.l1.p1.x - self.l1.p2.x) ** 2 + (self.l1.p1.y - self.l1.p2.y) ** 2)
d2 = math.sqrt((self.l2.p1.x - self.l2.p2.x) ** 2 + (self.l2.p1.y - self.l2.p2.y) ** 2)
d3 = math.sqrt((self.l3.p1.x - self.l3.p2.x) ** 2 + (self.l3.p1.y - self.l3.p2.y) ** 2)
return d1 + d2 > d3 and d1 + d3 > d2 and d2 + d3 > d1
# 计算面积
def area(self):
d1 = math.sqrt((self.l1.p1.x - self.l1.p2.x) ** 2 + (self.l1.p1.y - self.l1.p2.y) ** 2)
d2 = math.sqrt((self.l2.p1.x - self.l2.p2.x) ** 2 + (self.l2.p1.y - self.l2.p2.y) ** 2)
d3 = math.sqrt((self.l3.p1.x - self.l3.p2.x) ** 2 + (self.l3.p1.y - self.l3.p2.y) ** 2)
p = (d1 + d2 + d3) / 2
return math.sqrt(p * (p - d1) * (p - d2) * (p - d3))
# 输出显示
def display(self):
if self.is_triangle():
print('这是一个三角形,面积为:', self.area())
else:
print('这不是一个三角形。')
使用示例:
# 创建点对象
p1 = Point(0, 0)
p2 = Point(0, 1)
p3 = Point(1, 0)
# 创建线段对象
l1 = Line(p1, p2)
l2 = Line(p2, p3)
l3 = Line(p3, p1)
# 创建三角形对象
t = Triangle(l1, l2, l3)
# 复制构造函数
t_copy = Triangle(t)
# 输出显示
t.display() # 这是一个三角形,面积为: 0.5
t_copy.display() # 这是一个三角形,面积为: 0.5
# 修改点的坐标
p1.x = 1
p1.y = 1
# 输出显示
t.display() # 这不是一个三角形。
t_copy.display() # 这是一个三角形,面积为: 0.5
原文地址: https://www.cveoy.top/t/topic/lw86 著作权归作者所有。请勿转载和采集!