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