python實(shí)現(xiàn)輸入三角形邊長自動(dòng)作圖求面積案例
三角形是個(gè)好東西,比如知道三條邊邊長,可以判斷能不能組成三角形(兩邊之和大于第三邊),如果可以就進(jìn)一步計(jì)算其面積(海倫公式),最后還能把這個(gè)三角形畫出來(余弦定理求角度),所以說這個(gè)作為一個(gè)編程題目用于教學(xué)是比較棒的。
在jupyterlab中運(yùn)行效果如下:
python源代碼如下:
# %matplotlib inline# 建議在jupyterlab中運(yùn)行 import mathimport numpy as npimport matplotlib.pyplot as plt def judge(lines): '''判斷是否能組成三角形''' flag = 0 for i in range(3): l1 = lines.copy() # 要copy,不然會(huì)對(duì)源進(jìn)行修改 r = l1.pop(i) # r被取出,l1剩余倆 if (r>=sum(l1)): print('輸入的邊長無法構(gòu)成三角形') 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 # 計(jì)算角度 lines = [a,b,c] idx_A = np.argmax(lines) A = lines.pop(idx_A) # 最長邊作為底部邊長,最左側(cè)與坐標(biāo)軸原點(diǎn)對(duì)齊 B,C = lines # 根據(jù)三邊長求兩個(gè)水平夾角角度 cos_C = (A**2+B**2-C**2)/(2*A*B) cos_B = (A**2+C**2-B**2)/(2*A*C) # 根據(jù)余弦值求得正切值 k_C = math.tan(math.acos(cos_C)) k_B = math.tan(math.acos(cos_B)) # 根據(jù)正切值和高,獲得邊長 w_C = height/k_C w_B = height/k_B # 確定三個(gè)頂點(diǎn)的坐標(biāo) 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) # 保證兩條坐標(biāo)軸scale一致 plt.axis(’off’) # 關(guān)閉顯示直角坐標(biāo)系 plt.savefig('./trianle.png',dpi=300) print('三角形面積為:%.4f'%(area)) if __name__=='__main__': plot_triangle()
補(bǔ)充知識(shí):Python 三角形類,實(shí)現(xiàn)數(shù)據(jù)的輸入、輸出、周長、面積的計(jì)算
我就廢話不多說了,還是直接看代碼吧!
import mathclass 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('不符合三角邊的規(guī)定,重新輸入!')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實(shí)現(xiàn)輸入三角形邊長自動(dòng)作圖求面積案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決python腳本中error: unrecognized arguments: True錯(cuò)誤2. Python使用jupyter notebook查看ipynb文件過程解析3. PHP8.0新功能之Match表達(dá)式的使用4. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. Nginx+php配置文件及原理解析6. ajax請(qǐng)求添加自定義header參數(shù)代碼7. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. php測試程序運(yùn)行速度和頁面執(zhí)行速度的代碼10. 解決Python 進(jìn)程池Pool中一些坑
