一张不够花、 发表于 2023-3-31 19:57:07

请教大神

画出一个任意三角形并计算其面积。边长从键盘输入。(输入的边长要满足构成三角形的条件)

歌者文明清理员 发表于 2023-3-31 20:02:23

你什么意思直接抛题目啊

一张不够花、 发表于 2023-3-31 20:11:40

歌者文明清理员 发表于 2023-3-31 20:02
你什么意思直接抛题目啊

就是用turtle库画一个三角形并且写一个代码计算它的面积

isdkz 发表于 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)

    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("输入的边长不能构成三角形,请重新输入!")

傻眼貓咪 发表于 2023-3-31 20:34:18

import turtle
import math

# 创建一个 Turtle 实例
t = turtle.Turtle()

# 输入三角形的三边长
a = float(input("请输入第一条边长: "))
b = float(input("请输入第二条边长: "))
c = float(input("请输入第三条边长: "))

# 计算三角形内角和是否为180度
if a + b > c and a + c > b and b + c > a:
    # 计算三角形的周长和半周长
    p = a + b + c
    s = p / 2
    # 使用海伦公式计算三角形的面积
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))
    # 计算余弦定理中的角度值
    cosA = (b**2 + c**2 - a**2) / (2 * b * c)
    cosB = (a**2 + c**2 - b**2) / (2 * a * c)
    cosC = (a**2 + b**2 - c**2) / (2 * a * b)
    # 使用反余弦函数计算角度
    A = math.degrees(math.acos(cosA))
    B = math.degrees(math.acos(cosB))
    C = math.degrees(math.acos(cosC))
    # 绘制三角形
    t.forward(a)
    t.left(180 - C)
    t.forward(b)
    t.left(180 - A)
    t.forward(c)
    t.left(180 - B)

    print(f"三角形的面积为:{area}")
else:
    print("这三条边无法构成一个三角形!")

# 隐藏画笔
t.hideturtle()

# 保持窗口打开
turtle.done()

一张不够花、 发表于 2023-3-31 21:01:41

傻眼貓咪 发表于 2023-3-31 20:34


谢谢大佬
页: [1]
查看完整版本: 请教大神