如何用Python从变量中创建三角形图形

2024-06-16 08:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近刚刚投身于编程领域,并得到了一个非常基本的练习来完成,但我有点卡住了,不知道下一步该怎么做。 问题是:给定3个数字决定它们是否可以形成三角形,如果可以,则计算周长和面积,然后绘制三角形。 我已经设法计算出三角形的周长和面积(是否存在),但不知道如何使计算机从输入的任何值中画出三角形。

代码如下:

import math
a = int(input("Enter your first number"))
b = int(input("Enter your second number"))
c = int(input("Enter your third number"))
if a+b>c and a+c>b and b+c>a:
    print("The Triangle's Perimeter is:")
    print(int(a+b+c))
    print("The Area of the triangle is:")
    print(int(math.sqrt((a+b+c)/2)*(((a+b+c)/2)-a)*(((a+b+c)/2)-b)*(((a+b+c)/2)-c)))
else:
    print("The numbers do not form a triangle")
input("Press any key to continue")

希望你们能给我一个关于如何完成这项任务的见解


Tags: andthenumberinputyourismathint
3条回答

如果使用顶点的(x,y)坐标绘制,则至少有三个连续的自由度:2个用于选择顶点A的位置,另一个用于从A到B的方向。然后,有一个用于标记顶点的顺时针或逆时针顺序的二进制选择。

如果你不在乎使用哪一个,那么你可以把A放在(0,0),B放在(0,c),然后求解两个圆的交集:半径A以B为中心,半径B以A为中心

x² + y² = b² 
(x - c)² + y² = a² .... subtract these to eliminate y² 
(x - c)² - x² = a² - b²
-2cx + c² = a² - b²
2cx = c² + b² - a²
x = (c² + b² - a²)/(2c)
y = ± √[ b² - x² ] .... choose - for clockwise, + for counter-clockwise

现在有三个点A=(0,0),B=(0,c)和c=(x,y),分别对应于所需的对边长度A,B,c。如果需要角度,请使用trig中的余弦定律:

c² = a² + b² - 2ab(cos C)
2ab(cos C) = a² + b² - c²
C = cos⁻¹[ (a² + b² - c²)/(2ab) ]

同样的模式也适用于A和B的求解,它们是内角。对于海龟来说,旋转角度是外角,所以从A点开始,向任何方向移动(c),旋转(180-B),然后移动(A),然后旋转(180-B),然后移动(B)。

from turtle import color, begin_fill, forward, left, end_fill, done
from math import acos, degrees

def triangle_exists(a, b, c):
    """Return True iff there exists a triangle with sides a, b, c."""
    return a + b > c and b + c > a and c + a > b

def triangle_angle(a, b, c):
    """Return the angle (in degrees) opposite the side of length a in the
    triangle with sides a, b, c."""
    # See http://en.wikipedia.org/wiki/Law_of_cosines
    return degrees(acos((b ** 2 + c ** 2 - a ** 2) / (2.0 * b * c)))

def draw_triangle(a, b, c):
    """Draw a triangle with sides of lengths a, b, and c."""
    assert(triangle_exists(a, b, c))
    color('black', 'yellow')
    begin_fill()
    forward(c)
    left(180 - triangle_angle(b, c, a))
    forward(a)
    left(180 - triangle_angle(c, a, b))
    forward(b)
    end_fill()
    done()

>>> draw_triangle(400, 350, 200)

enter image description here

下面是另一个使用Tkinter的解决方案:

from Tkinter import *

def draw(a, b, c):
    # determine corner points of triangle with sides a, b, c
    A = (0, 0)
    B = (c, 0)
    hc = (2 * (a**2*b**2 + b**2*c**2 + c**2*a**2) - (a**4 + b**4 + c**4))**0.5 / (2.*c)
    dx = (b**2 - hc**2)**0.5
    if abs((c - dx)**2 + hc**2 - a**2) > 0.01: dx = -dx # dx has two solutions
    C = (dx, hc)

    # move away from topleft, scale up a bit, convert to int
    coords = [int((x + 1) * 75) for x in A+B+C]

    # draw using Tkinter
    root = Tk()
    canvas = Canvas(root, width=500, height=300)
    canvas.create_polygon(*coords)
    canvas.pack()
    root.mainloop()

draw(2, 4, 5)

enter image description here

相关问题 更多 >