如何在Python中使用我的变量创建一个三角形绘图

时间:2013-10-07 12:47:32

标签: 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")

如果你们能让我了解如何完成这项任务,那会很高兴吗

3 个答案:

答案 0 :(得分:6)

这是使用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

答案 1 :(得分:4)

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

答案 2 :(得分:-1)

如果使用顶点的(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)