|
发表于 2023-3-31 20:24:11
|
显示全部楼层
本帖最后由 isdkz 于 2023-3-31 20:25 编辑
- import math
- import matplotlib.pyplot as plt
- import matplotlib
- def is_valid_triangle(a, b, c):
- return a + b > c and a + c > b and b + c > a
- def calculate_area(a, b, c):
- s = (a + b + c) / 2
- area = math.sqrt(s * (s - a) * (s - b) * (s - c))
- return area
- def draw_triangle(a, b, c, area):
- coords = [(0, 0), (a, 0)]
- B_angle = math.acos((a**2 + b**2 - c**2) / (2 * a * b))
- bx = b * math.cos(B_angle)
- by = b * math.sin(B_angle)
- coords.append((bx, by))
- coords.append(coords[0])
- plt.plot(*zip(*coords), marker='o')
- plt.gca().set_aspect('equal', adjustable='box')
- # 设置字体支持中文
- matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei']
- matplotlib.rcParams['axes.unicode_minus'] = False
- # 计算文本位置,使其位于三角形内部
- text_x = a / 2
- text_y = by / 2
- plt.text(text_x, text_y, f"面积:{area:.2f}", fontsize=12, ha='center', va='center')
- plt.show()
- if __name__ == "__main__":
- a = float(input("请输入三角形的第一条边长:"))
- b = float(input("请输入三角形的第二条边长:"))
- c = float(input("请输入三角形的第三条边长:"))
- if is_valid_triangle(a, b, c):
- area = calculate_area(a, b, c)
- print(f"三角形的面积为:{area:.2f}")
- draw_triangle(a, b, c, area)
- else:
- print("输入的边长不能构成三角形,请重新输入!")
复制代码 |
|