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