国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python實(shí)現(xiàn)輸入三角形邊長自動作圖求面積案例

瀏覽:41日期:2022-07-30 11:13:41

三角形是個好東西,比如知道三條邊邊長,可以判斷能不能組成三角形(兩邊之和大于第三邊),如果可以就進(jìn)一步計(jì)算其面積(海倫公式),最后還能把這個三角形畫出來(余弦定理求角度),所以說這個作為一個編程題目用于教學(xué)是比較棒的。

在jupyterlab中運(yùn)行效果如下:

python實(shí)現(xià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,不然會對源進(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)對齊 B,C = lines # 根據(jù)三邊長求兩個水平夾角角度 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 # 確定三個頂點(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ǔ)充知識: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)輸入三角形邊長自動作圖求面積案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 台中县| 景宁| 岱山县| 顺平县| 凌云县| 镇宁| 曲麻莱县| 睢宁县| 揭东县| 当涂县| 石河子市| 武胜县| 安岳县| 武陟县| 大足县| 如东县| 汤阴县| 澄江县| 平南县| 姜堰市| 海门市| 延长县| 桐庐县| 乳源| 田林县| 藁城市| 保定市| 万宁市| 准格尔旗| 朝阳区| 曲阜市| 彰化市| 安图县| 九江县| 聂拉木县| 科技| 上虞市| 彭水| 巨野县| 新宾| 天等县|