1. 程式人生 > 程式設計 >python實現輸入三角形邊長自動作圖求面積案例

python實現輸入三角形邊長自動作圖求面積案例

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

在jupyterlab中執行效果如下:

python實現輸入三角形邊長自動作圖求面積案例

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,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,height],"gray")
  plt.plot([0,[0,"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實現輸入三角形邊長自動作圖求面積案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。