這篇文章主要講解了python實現輸入三角形邊長自動作圖求面積的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
三角形是個好東西,比如知道三條邊邊長,可以判斷能不能組成三角形(兩邊之和大于第三邊),如果可以就進一步計算其面積(海倫公式),最后還能把這個三角形畫出來(余弦定理求角度),所以說這個作為一個編程題目用于教學是比較棒的。
在jupyterlab中運行效果如下:

python源代碼如下:
# %matplotlib inline
# 建議在jupyterlab中運行
import math
import numpy as np
import matplotlib.pyplot as plt
def judge(lines):
"""判斷是否能組成三角形"""
flag = 0
for i in range(3):
l1 = lines.copy() # 要copy,不然會對源進行修改
r = l1.pop(i) # r被取出,l1剩余倆
if (r>=sum(l1)):
print("輸入的邊長無法構成三角形")
break
else:
flag += 1
continue
if flag==3:
return True
else:
return False
def plot_triangle():
lines = input("輸入三條邊長并用空格隔開:")
params = lines.split(" ")
lines = list(map(lambda x:float(x),params))
if judge(lines):
p = sum(lines)/2
a,b,c = lines
area = math.sqrt(p*(p-a)*(p-b)*(p-c))
width = max(lines)
height = area/width*2
# 計算角度
lines = [a,b,c]
idx_A = np.argmax(lines)
A = lines.pop(idx_A)
# 最長邊作為底部邊長,最左側與坐標軸原點對齊
B,C = lines
# 根據三邊長求兩個水平夾角角度
cos_C = (A**2+B**2-C**2)/(2*A*B)
cos_B = (A**2+C**2-B**2)/(2*A*C)
# 根據余弦值求得正切值
k_C = math.tan(math.acos(cos_C))
k_B = math.tan(math.acos(cos_B))
# 根據正切值和高,獲得邊長
w_C = height/k_C
w_B = height/k_B
# 確定三個頂點的坐標
loc_A = (0,height)
loc_B = (-w_B,0)
loc_C = (w_C,0)
plt.figure(figsize=(4,3))
plt.plot([0,-w_B,w_C,0],[height,0,0,height],"gray")
plt.plot([0,0],[0,height],"r--")
plt.text(1,height/2,"h=%.1f"%(height),color="blue",fontsize=12)
ax = plt.gca()
ax.set_aspect(1) # 保證兩條坐標軸scale一致
plt.axis('off') # 關閉顯示直角坐標系
plt.savefig("./trianle.png",dpi=300)
print("三角形面積為:%.4f"%(area))
if __name__=="__main__":
plot_triangle()補充知識:Python 三角形類,實現數據的輸入、輸出、周長、面積的計算
我就廢話不多說了,還是直接看代碼吧!
import math
class Triangle:
def __init__(self):
a=0
b=0
c=0
def add(self):
self.a=int(input("輸入第1條邊的長度:"))
self.b=int(input("輸入第2條邊的長度:"))
self.c=int(input("輸入第3條邊的長度:"))
while (self.a+self.b<=self.c):
print("不符合三角邊的規定,重新輸入!")
self.a=int(input("輸入第1條邊的長度:"))
self.b=int(input("輸入第2條邊的長度:"))
self.c=int(input("輸入第3條邊的長度:"))
def out(self):
print (self.a,self.b,self.c)
def length(self):
print (self.a+self.b+self.c)
def area(self):
print ((((a+b+c)/2)-a)*(((a+b+c)/2)-b)*(((a+b+c)/2)-c)*((a+b+c)/2))
t=Triangle()
t.add()
t.out()
t.length()
t.area()看完上述內容,是不是對python實現輸入三角形邊長自動作圖求面積的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。