用例子寫一個 Python 程序來尋找直角三角形的面積。在我們進入 Python 程序尋找直角三角形的面積之前,讓我們看看定義和公式
直角三角形的 Python 面積
如果我們知道寬度和高度,我們可以用下面的公式計算直角三角形的面積。
面積= (1/2) 寬度高度
利用畢達哥拉斯公式,我們可以很容易地找到直角三角形中未知的邊。
c = a + b
周長是邊緣周圍的距離。我們可以用下面的公式計算周長
周長= a + b+ c
尋找直角三角形面積的 Python 程序
這個 python 程序允許用戶輸入直角三角形的寬度和高度。使用這些值,我們將計算直角三角形的面積和周長。
# Python Program to find Area of a Right Angled Triangle
import math
width = float(input('Please Enter the Width of a Right Angled Triangle: '))
height = float(input('Please Enter the Height of a Right Angled Triangle: '))
# calculate the area
Area = 0.5 * width * height
# calculate the Third Side
c = math.sqrt((width*width) + (height*height))
# calculate the Perimeter
Perimeter = width + height + c
print("\n Area of a right angled triangle is: %.2f" %Area)
print(" Other side of right angled triangle is: %.2f" %c)
print(" Perimeter of right angled triangle is: %.2f" %Perimeter)
直角三角形輸出的 Python 面積
Please Enter the Width of a Right Angled Triangle: 7
Please Enter the Height of a Right Angled Triangle: 8
Area of a right angled triangle is: 28.00
Other side of right angled triangle is: 10.63
Perimeter of right angled triangle is: 25.63
首先,我們使用以下語句導入了數學庫。這將允許我們使用數學函數,如 math.sqrt 函數
import math
遵循 Python 語句將允許用戶輸入直角三角形的寬度和高度。
width = float(input('Please Enter the Width of a Right Angled Triangle: '))
height = float(input('Please Enter the Height of a Right Angled Triangle: '))
接下來,我們計算面積(1/2 = 0.5 的值)。所以我們用 0.5 寬高作為公式
Area = 0.5 * width * height
在下一行中,我們使用畢達哥拉斯公式 C =a +b 計算直角三角形的另一邊,類似於 C = √a +b
c = math.sqrt((width*width) + (height*height))
這裡我們用 sqrt()函數計算 a +b 的平方根,sqrt()是數學函數,用來計算平方根。
在下一行,我們使用公式計算周長
Perimeter = width + height + c
以下列印語句將幫助我們列印直角三角形的周長、其他邊和面積
print("\n Area of a right angled triangle is: %.2f" %Area)
print(" Other side of right angled triangle is: %.2f" %c)
print(" Perimeter of right angled triangle is: %.2f" %Perimeter)
用函數求直角三角形面積的 Python 程序
這個 python 程序允許用戶輸入直角三角形的寬度和高度。我們將把這些值傳遞給函數參數,以計算 Python 中直角三角形的面積。
# Python Program to find Area of a Right Angled Triangle using Functions
import math
def Area_of_a_Right_Angled_Triangle(width, height):
# calculate the area
Area = 0.5 * width * height
# calculate the Third Side
c = math.sqrt((width * width) + (height * height))
# calculate the Perimeter
Perimeter = width + height + c
print("\n Area of a right angled triangle is: %.2f" %Area)
print(" Other side of right angled triangle is: %.2f" %c)
print(" Perimeter of right angled triangle is: %.2f" %Perimeter)
Area_of_a_Right_Angled_Triangle(9, 10)
首先,我們使用 def 關鍵字定義了帶有兩個參數的函數。這意味著,用戶將輸入直角三角形的寬度和高度。接下來,我們計算一個直角三角形的面積,正如我們在第一個例子中描述的那樣。
原創文章,作者:DZEQG,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129290.html