用于计算立方体体积的 Python 程序

pythonserver side programmingprogramming更新于 2024/2/22 14:02:00

立方体是一种三维立体图形,有六个面、十二条边和八个顶点。这种几何图形的边大小相等,因此其所有尺寸(长度、宽度和高度)都相等。

计算立方体体积的想法可以用一种简单的方式理解。考虑一个人搬家的实时情况。假设他们使用一个空心立方体形状的纸板箱来放置他们的东西,填充它的空间量被定义为体积。

计算边长为"a"的立方体体积的数学公式如下 -

(a)*(a)*(a)

输入输出场景

用于计算立方体体积的python程序将提供以下输入输出场景 -

假设立方体边缘的长度为正,则输出为 -

输入:6 // 6是边长
结果:立方体的体积= 216

假设立方体边长为负,则输出结果为 −

输入:-6 // -6 为边长
结果:长度无效

使用数学公式

如上所示,计算立方体体积的公式相对简单。因此,我们编写一个 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


相关文章