如何用例子編寫 Python 程序求三角形的面積、周長和半周長?在我們進入 Python 程序尋找三角形面積之前,讓我們看看三角形周長和面積後面的定義和公式。
三角形的面積
如果我們知道一個三角形的三條邊的長度,那麼我們就可以用赫倫公式 來計算三角形的面積
三角形的面積= √(s(s-a)(s-b)*(s-c))
其中 s = (a + b + c )/ 2(這裡 s =半周長,a、b、c 是三角形的三條邊)
三角形的周長= a + b + c
尋找三角形面積和三角形周長的 Python 程序
這個 Python 程序允許用戶輸入三角形的三條邊。使用這些值,我們將計算三角形的周長,三角形的半周長,然後三角形的面積。
a = float(input('Please Enter the First side of a Triangle: '))
b = float(input('Please Enter the Second side of a Triangle: '))
c = float(input('Please Enter the Third side of a Triangle: '))
# calculate the Perimeter
Perimeter = a + b + c
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
Area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print("\n The Perimeter of Traiangle = %.2f" %Perimeter);
print(" The Semi Perimeter of Traiangle = %.2f" %s);
print(" The Area of a Triangle is %0.2f" %Area)
前三個 Python 語句將允許用戶輸入三角形 a、b、c 的三條邊。接下來,使用公式 P = a+b+c 計算三角形的周長。
# calculate the Perimeter
Perimeter = a + b + c
接下來,使用公式(a+b+c)/2 計算半周長。雖然我們可以寫半周長=(周長/2),但我們想展示後面的公式。這就是為什麼我們使用標準公式
s = (a + b + c) / 2
使用 Heron 公式計算三角形的面積:
(s*(s-a)*(s-b)*(s-c)) ** 0.5
用函數求三角形面積的 Python 程序
這個 python 程序允許用戶輸入三角形的三條邊。我們將把這三個值傳遞給函數參數,以計算 Python 中三角形的面積。
# Area of a Triangle using Functions
import math
def Area_of_Triangle(a, b, c):
# calculate the Perimeter
Perimeter = a + b + c
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
Area = math.sqrt((s*(s-a)*(s-b)*(s-c)))
print("\n The Perimeter of Traiangle = %.2f" %Perimeter);
print(" The Semi Perimeter of Traiangle = %.2f" %s);
print(" The Area of a Triangle is %0.2f" %Area)
Area_of_Triangle(6, 7, 8)
Python 三角形面積輸出
The Perimeter of Traiangle = 21.00
The Semi Perimeter of Traiangle = 10.50
The Area of a Triangle is 20.33
>>> Area_of_Triangle(10, 9, 12)
The Perimeter of Traiangle = 31.00
The Semi Perimeter of Traiangle = 15.50
The Area of a Triangle is 44.04
>>>
首先,我們使用以下語句導入了數學庫。這將允許我們使用數學函數,如 math.sqrt 函數
import math
步驟 2:接下來,我們使用 def 關鍵字定義了具有三個參數的函數。意思是,用戶將輸入三角形 a、b、c 的三條邊
第三步:利用 Heron 公式計算三角形的面積:sqrt(s (s-a)(s-b)*(s-c));(sqrt()是數學庫中的數學函數,用於計算平方根。
注意:在放置開括弧和閉括弧時請小心,如果放置錯誤,可能會改變整個計算
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254333.html