#填充儿童球坑所需球的数量可以计算为:球坑的体积除以单个球的体积乘以填充密度。
#填料密度一般为0.75。
#球坑体积计算公式为:Pi (3.14) * radius2 *球坑高度
#球的体积计算公式为:(4/3)* Pi (3.14) * radius3.
#编写一个函数,根据球坑半径和球坑高度两个参数返回球坑的体积
#写一个函数从一个参数返回一个球的体积:球的半径
#程序应输出使用0.05m球填充半径为1m,高度为0.2m的坑所需的球数
import math
packing_density=0.75
def volume_of_ball_pit():
radius_pit= float(input("Input the radius of the pit"))
height_pit= float(input("Input the height of the ball pit"))
volume_pit= math.pi * radius_pit * height_pit
return volume_pit
def volume_of_ball():
radius_ball= float(input("Input the radius of the ball"))
volume_ball= (math.pi*(4/3))*radius_ball
return volume_ball
def balls_required():
volume_of_ball_pit()
volume_of_ball()
number_of_balls= (volume_pit/volume_ball)*packing_density
balls_required()
我收到一个错误,我的变量没有定义,但是,我认为它已经在前面的子程序中完成了,有什么提示吗?
你必须把函数的结果赋值给变量
def balls_required():
volume_pit = volume_of_ball_pit()
volume_ball = volume_of_ball()
number_of_balls= (volume_pit/volume_ball)*packing_density
变量不能在不同的def(函数)中看到彼此,除非您将它们设置为全局:
在代码开头设置变量为全局变量:
global radius_pit,height_pit,volume_pit, number_of_balls,
首先,球体(这里是球)的体积计算公式为:(4/3)* pi * (r^3),凹坑(我假设是圆柱体)的体积计算公式为:pi * (r^2) * h
实际代码应该是这样:
import math
packing_density=0.75
def volume_of_ball_pit():
radius_pit= float(input("Input the radius of the pit"))
height_pit= float(input("Input the height of the ball pit"))
volume_pit= math.pi * radius_pit *radius_pit * height_pit
return volume_pit
def volume_of_ball():
radius_ball= float(input("Input the radius of the ball"))
volume_ball= (math.pi*(4/3))*radius_ball**3
return volume_ball
def balls_required():
number_of_balls= (volume_of_ball_pit()/volume_of_ball())*packing_density
print(number_of_balls)
if __name__ == '__main__':
balls_required()
这可能是解释器显示变量未定义的原因。