我正在为一个类编写一个程序,以在从用户输入半径和高度的情况下找到平截头体的体积和表面积。我认为自己走在正确的道路上,但是对于如何将公式放入python中,我并不自信。用于查找表面积的公式为:
这是我的代码:
import math
def main():
radius1Length = float(input("Please enter the first radius:"))
radius2Length = float(input("Please enter the second radius:"))
heightNum = float(input("Please enter the height:"))
volumeTotal = volume(radius1Length,radius2Length,heightNum)
sAreaTotal = surfaceArea(radius1Length,radius2Length,heightNum)
print("The radius values used were:", radius1Length, "and", radius2Length)
print("The height used was:", heightNum)
print("The volume is:", volumeTotal)
print("The surace area is:", sAreaTotal)
## Compute the volume of a frustum
# @pram radius1 a float giving the length of the first radius value
# @pram radius2 a float giving the length of the second radius value
# @pram height a float giving the height value
# @return the volume of the frustum as a float
def volume(radius1,radius2,height):
volumeValue = (1/3) * math.pi * height * (radius1**2 + radius2**2 + (radius1 * radius2))
return volumeValue
## Compute the surface area of a frustum
# @pram radius1 a float giving the length of the first radius value
# @pram radius2 a float giving the length of the second radius value
# @pram height a flot givign the height value
# @raturn the surface area of the frustum as a float
def surfaceArea(radius1,radius2,height):
sArea = math.pi * ((radius1 + radius2) * math.sqrt( height**2 + ((radius2 - radius1)**2) + (math.pi * (radius1**2))))
return sArea
main()
如果有人甚至可以确认这是在python中写出该公式的正确方法,将不胜感激
答案 0 :(得分:2)
锥体的表面积不应该是吗?
pi * (radius1 + radius2) * sqrt((radius2-radius1)**2 + height**2) + pi * (radius1**2) + pi * (radius2**2)
除了括号放置错误之外,您还错过了pi * (radius2**2)
吗?
答案 1 :(得分:0)
括号有问题。您写道:
sArea = pi * ((r1+r2) * sqrt(h**2 + ((r2-r1)**2) + (pi * (r1**2))))
对应于:
您注意到,pi * (r1 ** 2)
也放在平方根下,这是不正确的。
您可以将其重写为:
from math import pi, sqrt
def surfaceArea(r1, r2, h):
return pi * (r1 + r2) * sqrt((r2-r1)**2 + h*h) + pi * r1 * r1
或更详细:
from math import pi, sqrt
def surfaceArea(radius1, radius2, h):
return pi * (radius1 + radius2) * sqrt((radius2-radius1)**2 + height**2) + pi * (radius1**2)
但是实际上写x * x
通常比写x ** 2
更有效率(而且在数值上正确)。
编辑:
您提供的公式不正确。公式是:
我们可以这样实现:
from math import pi, sqrt
def surfaceArea(r1, r2, h):
return pi * ((r1 + r2) * sqrt((r2-r1)**2 + h*h) + r1*r1 + r2*r2)