Python程式計算立方體的體積
立方體是一個三維立體圖形,具有六個面、十二條邊和八個頂點。這個幾何圖形的邊長相等,因此它的所有尺寸——長度、寬度和高度——都相等。
計算立方體體積的概念可以很容易理解。考慮一個現實生活中的場景,一個人正在搬家。假設他們使用一個空心的立方體形狀的紙板箱來放置他們的物品,那麼填充它的空間量就被定義為體積。

計算邊長為“a”的立方體體積的數學公式如下:
(a)*(a)*(a)
輸入輸出場景
用於計算立方體體積的Python程式將提供以下輸入輸出場景:
假設立方體邊長為正數,則輸出為:
Input: 6 // 6 is the edge length Result: Volume of the cube = 216
假設立方體邊長為負數,則輸出為:
Input: -6 // -6 is the edge length Result: Not a valid length
使用數學公式
如上所示,計算立方體體積的公式相對簡單。因此,我們編寫一個Python程式,透過獲取立方體邊長作為輸入來顯示體積。
示例
在下面的Python程式碼中,我們使用其數學公式計算立方體體積,並且立方體的邊長作為輸入。
#length of the cube edge cube_edge = 5 #calculating the volume cube_volume = (cube_edge)*(cube_edge)*(cube_edge) #displaying the volume print("Volume of the cube: ", str(cube_volume))
輸出
以上Python程式碼的輸出顯示了立方體的體積。
Volume of the cube: 125
計算體積的函式
在Python中計算立方體體積的另一種方法是使用函式。Python有各種內建函式,但也有宣告使用者定義函式的規定。我們使用def關鍵字宣告函式,並且可以傳遞任意數量的引數。在宣告Python函式時,不需要提及返回值型別。
宣告函式的語法如下:
def function_name(arguments separated using commas)
示例
在下面的Python程式中,
#function to calculate volume of a cube def volume(cube_edge): #calculating the volume cube_volume = (cube_edge)*(cube_edge)*(cube_edge) #displaying the volume print("Volume of the cube: ", str(cube_volume)) #calling the volume function volume(5) #length of an edge = 5
輸出
執行以上Python程式碼後,輸出顯示為:
Volume of the cube: 125
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP