如何用例子編寫 Python 程序求梯形面積和梯形中值?在我們進入實際的 Python 程序尋找梯形面積的例子之前,讓我們看看定義和公式
梯形的 Python 面積
如果我們知道高度和兩個底長,那麼我們可以用下面的公式計算梯形的面積:
面積= (a+b)/2 * h
其中 a 和 b 是兩個底,h 是梯形的高度。我們可以用下面的公式計算梯形的中值:
中位數= (a+b) / 2。
如果我們知道中間值和高度,那麼我們可以計算梯形的面積為:中間值*高度
尋找梯形面積的 Python 程序
這個 python 程序允許用戶輸入梯形的兩邊和高度。使用這些值,這個 Python 程序將計算梯形的面積和梯形的中值。
# Python Program to find Area of a Trapezoid
base1 = float(input('Please Enter the First Base of a Trapezoid: '))
base2 = float(input('Please Enter the Second Base of a Trapezoid: '))
height = float(input('Please Enter the Height of a Trapezoid: '))
# calculate the area
Area = 0.5 * (base1 + base2) * height
# calculate the Median
Median = 0.5 * (base1+ base2)
print("\n Area of a Trapezium = %.2f " %Area)
print(" Median of a Trapezium = %.2f " %Median)
以下語句將要求用戶輸入 base1、base2 和 height 值,並將用戶輸入值分配給相關變數。如第一個值將賦給 base1,第二個值賦給 base2,第三個值賦給高度
base1 = float(input('Please Enter the First Base of a Trapezoid: '))
base2 = float(input('Please Enter the Second Base of a Trapezoid: '))
height = float(input('Please Enter the Height of a Trapezoid: '))
接下來,我們使用它們各自的公式計算梯形的中值和面積:
# calculate the area
Area = 0.5 * (base1 + base2) * height
# calculate the Median
Median = 0.5 * (base1+ base2)
列印語句將幫助我們列印梯形的中值和面積
print("\n Area of a Trapezium = %.2f " %Area)
print(" Median of a Trapezium = %.2f " %Median)
讓我們看看程序的輸出
Please Enter the First Base of a Trapezoid: 6
Please Enter the Second Base of a Trapezoid: 9
Please Enter the Height of a Trapezoid: 4
Area of a Trapezium = 30.00
Median of a Trapezium = 7.50
從上面的 Python 截圖可以觀察到,我們輸入的值是 base1 = 6,base2 = 9,height = 4
梯形的面積= 0.5 (基底 1 +基底 2) 高度;
梯形的面積= 0.5 (6+9) 4;
梯形的面積= 0.5 15 4;
梯形面積= 30
梯形的中值= 0.5 (base 1+base 2);
梯形的中值= 0.5 (6 + 9)
梯形的中值= 0.5 * 15
梯形的中值= 7.5
用函數求梯形面積的 Python 程序
這個 python 程序允許用戶輸入梯形的基底 1、基底 2 和高度。我們將把這些值傳遞給函數參數來計算梯形的面積。
# Python Program to find Area of a Trapezoid using Functions
def Area_of_a_Trapezoid (base1, base2, height):
# calculate the area
Area = 0.5 * (base1 + base2) * height
# calculate the Median
Median = 0.5 * (base1+ base2)
print("\n Area of a Trapezium = %.2f " %Area)
print(" Median of a Trapezium = %.2f " %Median)
Area_of_a_Trapezoid (9, 6, 4)
在這個尋找梯形面積的 Python 程序示例中,首先,我們使用 def 關鍵字定義了具有三個參數的函數。這意味著,用戶將輸入梯形的底 1、底 2 和高度。接下來,我們計算梯形的中值和面積,正如我們在第一個例子中所描述的。
注意:我們可以用中的參數調用函數。或者我們可以從 python shell 中調用它。請不要忘記函數參數
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/232029.html