三维圆锥的表面积和体积
写一个程序,让用户输入一个三维圆锥的半径和高度,然后计算并打印出这个圆锥的表面积和体积。表面积和体积的计算会放在函数里,输入的收集也是如此。
这个程序的工作流程如下:
- 打印一条消息,说明这个程序的功能。
- 提示用户输入半径(一个非负的浮点数),单位是英尺。
- 提示用户输入高度(一个非负的浮点数),单位是英尺。
- 打印出半径和高度,保留两位小数。
- 打印出表面积和体积,保留两位小数。
这是我目前完成的部分:
import math
print("This Program will calculate the surface area and volume of a cone."
"\nPlease follow the directions.")
print()
print()
r = input(str("What is the radius in feet? (no negatives): "))
h = input(str("What is the height in feet? (no negatives): "))
math.pi = (22.0/7.0)
math.sqrt()
surfacearea = int(math.pi*r**2)+int(r*math.pi(math.sqrt(r**2+h**2)))
print("The surface area is", surfacearea)
print()
volume = (1/3)*math.pi*r**2*h
print ("The volume is", volume)
print()
print("Your Answer is:")
print()
print("A cone with radius", r, "\nand hieght", h,"\nhas a volume of : ",volume,
"\nand surface area of", surfacearea,)
我一直遇到错误
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
TypeError: can't multiply sequence by non-int of type 'float'
有没有人能帮我解决这个小问题?我觉得'float'可能是问题的一部分。我认为设置是好的,但执行时出现了问题。
1 个回答
2
我假设你在用Python 3,所以input
这个函数返回的就是一个字符串。
所以:
r = input(str("What is the radius in feet? (no negatives): "))
# ...
surfacearea = int(math.pi*r**2) #+ ...
这样会出现错误,因为你在尝试对一个字符串进行平方运算。这个是行不通的。
如果你在input
后面加上r = float(r)
,那么它就会把输入转换成一个浮点数(你可以对它进行平方),如果用户输入了不合适的内容,它会报错。
另外,那个str
在那一行是干嘛的?你觉得"What is the radius in feet? (no negatives): "
是什么类型?你是想实现什么,还是随便加上去的,连原因都不知道?
同样,在这一行:
surfacearea = int(math.pi*r**2)+int(r*math.pi(math.sqrt(r**2+h**2)))
你为什么要把浮点数转换成int
?题目说这些值应该“保留到小数点后两位”。
更一般来说,如果你在某行代码上遇到错误却不知道为什么,可以尝试把它拆开。那一行代码里发生了很多事情。为什么不试试这样:
r_squared = r**2
pi_r_squared = math.path * r_squared
int_pi_r_squared = int(pi_r_squared)
h_squared = h**2
r_squared_h_squared = r_squared + h_squared
sqrt_r2_h2 = math.sqrt(r_squared_h_squared)
# etc.
这样你就能看到哪个部分出问题了,并找出原因,而不必在一堆代码中猜来猜去。你甚至可以通过在特定行添加pdb
断点或print
语句来调试,确保每个值都是你预期的那样。