use*_*381 29 python string concatenation
我们的几何老师给了我们一个任务,要求我们创建一个玩具在现实生活中使用几何体的例子,所以我认为制作一个程序来计算需要多少加仑的水来填充某个池才是很酷的.形状,并具有一定的尺寸.
这是迄今为止的计划:
import easygui
easygui.msgbox("This program will help determine how many gallons will be needed to fill up a pool based off of the dimensions given.")
pool=easygui.buttonbox("What is the shape of the pool?",
choices=['square/rectangle','circle'])
if pool=='circle':
height=easygui.enterbox("How deep is the pool?")
radius=easygui.enterbox("What is the distance between the edge of the pool and the center of the pool (radius)?")
easygui.msgbox=("You need "+(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
Run Code Online (Sandbox Code Playgroud)
我不断得到这个错误:easygui.msgbox =("你需要"+(3.14*(浮动(半径)**2)*浮动(高度))+"加仑水来填充这个池.")TypeError:不能连接'str'和'float'对象
我该怎么办?
Kal*_*n02 40
在连接之前,必须将所有浮点数或非字符串数据类型转换为字符串
这应该正常工作:(注意str演员的乘法结果)
easygui.msgbox=("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
Run Code Online (Sandbox Code Playgroud)
直接从翻译:
>>> radius = 10
>>> height = 10
>>> msg = ("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")
>>> print msg
You need 3140.0gallons of water to fill this pool.
Run Code Online (Sandbox Code Playgroud)
还有一种解决方案,您可以使用字符串格式化(我猜类似于c语言)
这样您也可以控制精度。
radius = 24
height = 15
msg = "You need %f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)
msg = "You need %8.2f gallons of water to fill this pool." % (3.14 * (float(radius) ** 2) * float(height))
print(msg)
Run Code Online (Sandbox Code Playgroud)
没有精确性
您需要 27129.600000 加仑的水来填满这个水池。
精度8.2
您需要 27129.60 加仑的水来填满这个池。