Python程式計算立方體面積


要計算立方體的表面積,讓我們首先回顧一下立方體的概念。立方體是一個幾何圖形,包含三個維度:長、寬和高,所有維度都具有相同的測量值。它有六個正方形面,其中四個是側表面,另外兩個是立方體的頂部和底部表面。

找到表面積只需要知道單條邊的長度。立方體的面積可透過以下步驟計算:

  • 根據給定的邊長計算一個正方形面的面積

  • 找到的正方形面積的四倍是“側表面積

  • 找到的正方形面積的六倍是“總表面積

對於任何給定邊長為 'a' 的立方體,求表面積的數學公式如下:

Lateral Surface Area: 4*(a)*(a)
Total Surface Area: 6*(a)*(a)

輸入輸出場景

假設立方體邊長為正數,則輸出結果為:

Input: 6 // 6 is the edge length
Result: Lateral surface area: 144
Total surface area: 216

假設立方體邊長為負數,則輸出結果為:

Input: -6 // -6 is the edge length
Result: Not a valid length

使用數學公式

要使用數學公式在 Python 中計算立方體的面積,我們需要將立方體的任何邊長作為輸入。讓我們看下面的例子:

示例

在下面的 Python 程式中,我們計算了邊長用“cube_edge”表示的立方體的側表面積和總表面積。

#The length of an edge in the Cube cube_edge = 6 if(cube_edge > 0): #Calculating Lateral Surface Area of the Cube lsa = 4*(cube_edge)*(cube_edge) #Calculating Total Surface Area of the Cube tsa = 6*(cube_edge)*(cube_edge) #Displaying the surface areas of the Cube print("Lateral surface area: ", str(lsa)) print("Total surface area: ", str(tsa)) else: print("Not a valid length")

輸出

執行上面的 Python 程式後,輸出結果為:

Lateral surface area: 144
Total surface area: 216

計算表面積的函式

在 Python 中,我們還可以使用使用者定義的函式來顯示立方體的表面積。Python 中的函式使用def關鍵字宣告,透過逗號分隔的單個或多個引數進行傳遞。讓我們看看如何在下面的示例中找到立方體的表面積。

宣告函式的語法為:

def function_name(argument 1, argument 2, …)

示例

在下面的示例中,我們聲明瞭兩個函式來計算立方體的側表面積和總表面積。立方體邊長作為引數傳遞給這些函式。

#function to calculate lateral surface area def lateral_surfacearea(cube_edge): if(cube_edge > 0): lsa = 4*(cube_edge)*(cube_edge) print("Lateral surface area: ", str(lsa)) else: print("Not a valid length") #function to calculate total surface area def total_surfacearea(cube_edge): if(cube_edge > 0): tsa = 6*(cube_edge)*(cube_edge) print("Total surface area: ", str(tsa)) else: print("Not a valid length") lateral_surfacearea(4) #length of the edge = 4 total_surfacearea(4)

輸出

計算邊長為“4”的立方體的表面積後的輸出結果顯示為:

Lateral surface area: 64
Total surface area: 96

更新於:2022年10月14日

3K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告