无法连接“ str”和“ float”对象?

我们的几何老师给我们分配了一个作业,要求我们创建一个玩具在现实生活中何时使用几何的示例,因此我认为编写一个程序来计算填充一定数量的水池需要多少加仑水会很酷。形状,并具有一定的尺寸。


这是到目前为止的程序:


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.")

我一直收到此错误:


easygui.msgbox=("You need "+(3.14*(float(radius)**2) * float(height))


+ "gallons of water to fill this pool.")

TypeError: cannot concatenate 'str' and 'float' objects

我该怎么办?


HUWWW
浏览 569回答 3
3回答

PIPIONE

在连接之前,必须将所有浮点数或非字符串数据类型强制转换为字符串这应该可以正常工作:(请注意str强制转换为乘法结果)easygui.msgbox=("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")直接来自口译员:>>> radius = 10>>> height = 10>>> msg = ("You need "+ str(3.14*(float(radius)**2) * float(height)) + "gallons of water to fill this pool.")>>> print msgYou need 3140.0gallons of water to fill this pool.

慕尼黑5688855

使用Python3.6 +,您可以使用f字符串格式化打印语句。radius=24.0height=15.0print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")

红糖糍粑

还有另一种解决方案,您可以使用字符串格式设置(类似于我猜的C语言)这样,您也可以控制精度。radius = 24height = 15msg = "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)没有精度您需要27129.600000加仑水来填充该池。精度8.2您需要27129.60加仑的水来填充该池。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python