Python程式計算圓柱體的體積和表面積


在這篇文章中,我們將學習一個Python程式來計算圓柱體的體積和表面積。

圓柱體定義為一個三維物體,它有兩個圓透過矩形表面連線起來。圓柱體的特殊之處在於,儘管它只用兩個維度(即高度半徑)來測量,但由於它是在xyz座標軸上測量的,因此圓柱體被認為是三維圖形。

圓柱體的表面積計算有兩種方法——側表面積和總表面積。側表面積僅指連線底圓的矩形表面的面積,而總表面積是整個圓柱體的面積。

圓柱體的體積定義為該物體所包含的空間。

計算圓柱體表面積的數學公式如下:

Lateral Surface Area: 2πrh
Total Surface Area: 2πr(r + h)

計算圓柱體體積的公式如下:

Volume: πr2h

輸入輸出場景

計算圓柱體表面積和體積的Python程式將提供以下輸入輸出場景:

假設圓柱體的高度和半徑如下所示,則輸出結果為:

Input: (6, 5) // 6 is the height and 5 is the radius
Result: Lateral Surface Area of the cylinder: 188.49555921538757
Total Surface Area of the cylinder: 345.57519189487726
Volume of the cylinder: 471.2388980384689

使用數學公式

應用標準數學公式計算圓柱體的表面積和體積。我們需要圓柱體的高度和半徑的值,將它們代入公式中,得到這個三維物體的表面積和體積。

示例

在下面的示例程式碼中,我們從Python中匯入math庫,在求解面積和體積時使用pi常數。輸入被認為是圓柱形圖形的高度和半徑。

import math #height and radius of the cylinder height = 6 radius = 5 #calculating the lateral surface area cyl_lsa = 2*(math.pi)*(radius)*(height) #calculating the total surface area cyl_tsa = 2*(math.pi)*(radius)*(radius + height) #calculating the volume cyl_volume = (math.pi)*(radius)*(radius)*(height) #displaying the area and volume print("Lateral Surface Area of the cylinder: ", str(cyl_lsa)) print("Total Surface Area of the cylinder: ", str(cyl_tsa)) print("Volume of the cylinder: ", str(cyl_volume))

輸出

執行上述程式碼後,輸出結果顯示為:

Lateral Surface Area of the cylinder: 188.49555921538757
Total Surface Area of the cylinder: 345.57519189487726
Volume of the cylinder: 471.23889803846896

計算面積和體積的函式

我們還可以使用Python中的使用者自定義函式來計算面積和體積。這些Python函式是用def關鍵字宣告的,傳遞的引數是圓柱體的高度和半徑。讓我們看下面的例子。

示例

下面的Python程式使用函式來計算圓柱體的表面積和體積。

import math def cyl_surfaceareas(height, radius): #calculating the lateral surface area cyl_lsa = 2*(math.pi)*(radius)*(height) print("Lateral Surface Area of the cylinder: ", str(cyl_lsa)) #calculating the total surface area cyl_tsa = 2*(math.pi)*(radius)*(radius + height) print("Total Surface Area of the cylinder: ", str(cyl_tsa)) def cyl_volume(height, radius): #calculating the volume cyl_volume = (math.pi)*(radius)*(radius)*(height) #displaying the area and volume print("Volume of the cylinder: ", str(cyl_volume)) #height and radius of the cylinder height = 7 radius = 4 cyl_surfaceareas(height, radius) cyl_volume(height, radius)

輸出

執行Python程式碼後,輸出顯示錶面積和體積:

Lateral Surface Area of the cylinder: 175.92918860102841
Total Surface Area of the cylinder: 276.46015351590177
Volume of the cylinder: 351.85837720205683

更新於:2022年10月14日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告