5

私は最近プログラミングの世界に飛び込み、完了するための非常に基本的な演習を与えられましたが、ちょっと立ち往生していて、次に何をすべきかわかりません. 問題は次のとおりです。与えられた 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")

このタスクを達成する方法についての洞察を教えていただければ幸いです

4

3 に答える 3

7

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)

ここに画像の説明を入力

于 2013-10-07T13:44:12.030 に答える
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)

ここに画像の説明を入力

于 2013-10-07T13:31:08.477 に答える