📅  最后修改于: 2023-12-03 14:46:49.030000             🧑  作者: Mango
本题是关于三角形和其高度及距离的计算问题,需要计算出三角形的面积、周长、高度和内心到各边的距离等。
已知三角形 ABC,以及它的三个顶点的坐标 A(x1, y1)、B(x2, y2)、C(x3, y3),编写程序计算:
import math
def calc_area(x1, y1, x2, y2, x3, y3):
# 计算三角形的面积
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
p = (a + b + c) / 2
return math.sqrt(p * (p - a) * (p - b) * (p - c))
def calc_perimeter(x1, y1, x2, y2, x3, y3):
# 计算三角形的周长
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
return a + b + c
def calc_circumradius(x1, y1, x2, y2, x3, y3):
# 计算三角形外接圆半径
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
s = (a + b + c) / 2
return a * b * c / 4 / calc_area(x1, y1, x2, y2, x3, y3)
def calc_inradius(x1, y1, x2, y2, x3, y3):
# 计算三角形内切圆半径
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
p = (a + b + c) / 2
return calc_area(x1, y1, x2, y2, x3, y3) / p
def calc_distance_of_incenter_to_edges(x1, y1, x2, y2, x3, y3):
# 计算三角形内心到三条边的距离
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
p = (a + b + c) / 2
r = calc_inradius(x1, y1, x2, y2, x3, y3)
ha = 2 * calc_area(x1, y1, x2, y2, x3, y3) / a
hb = 2 * calc_area(x1, y1, x2, y2, x3, y3) / b
hc = 2 * calc_area(x1, y1, x2, y2, x3, y3) / c
x, y = calc_incenter(x1, y1, x2, y2, x3, y3)
d1 = abs(2 * calc_area(x, y, x1, y1, x2, y2) / a - r)
d2 = abs(2 * calc_area(x, y, x2, y2, x3, y3) / b - r)
d3 = abs(2 * calc_area(x, y, x3, y3, x1, y1) / c - r)
return d1, d2, d3
def calc_incenter(x1, y1, x2, y2, x3, y3):
# 计算三角形内心坐标
a = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
b = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
c = math.sqrt((x3 - x1)**2 + (y3 - y1)**2)
p = (a + b + c) / 2
s = calc_area(x1, y1, x2, y2, x3, y3)
x = (a * x1 + b * x2 + c * x3) / (a + b + c)
y = (a * y1 + b * y2 + c * y3) / (a + b + c)
return x, y
# 示例数据
x1, y1 = 0, 0
x2, y2 = 3, 4
x3, y3 = 4, 0
# 调用函数计算结果
area = calc_area(x1, y1, x2, y2, x3, y3)
perimeter = calc_perimeter(x1, y1, x2, y2, x3, y3)
circumradius = calc_circumradius(x1, y1, x2, y2, x3, y3)
inradius = calc_inradius(x1, y1, x2, y2, x3, y3)
d1, d2, d3 = calc_distance_of_incenter_to_edges(x1, y1, x2, y2, x3, y3)
# 输出结果
print('面积:', area)
print('周长:', perimeter)
print('外接圆半径:', circumradius)
print('内切圆半径:', inradius)
print('内心到三边距离:', d1, d2, d3)
输出结果应为:
面积: 6.0
周长: 12.0
外接圆半径: 2.5
内切圆半径: 1.0
内心到三边距离: 1.0 1.0 1.0