三角形是個好東西,比如知道三條邊邊長,可以判斷能不能組成三角形(兩邊之和大于第三邊),如果可以就進一步計算其面積(海倫公式),最後還能把這個三角形畫出來(餘弦定理求角度),是以說這個作為一個程式設計題目用于教學是比較棒的。
在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()