为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

HUWWW 2019-12-06 11:05:14
我们的几何老师给我们分配了一个作业,要求我们创建一个玩具在现实生活中何时使用几何的示例,因此我认为编写一个程序来计算填充一定数量的水池需要多少加仑水会很酷。形状,并具有一定的尺寸。这是到目前为止的程序:import easyguieasygui.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我该怎么办?
查看完整描述

3 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

在连接之前,必须将所有浮点数或非字符串数据类型强制转换为字符串


这应该可以正常工作:(请注意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 msg

You need 3140.0gallons of water to fill this pool.


查看完整回答
反对 回复 2019-12-06
?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

使用Python3.6 +,您可以使用f字符串格式化打印语句。


radius=24.0

height=15.0

print(f"You need {3.14*height*radius**2:8.2f} gallons of water to fill this pool.")


查看完整回答
反对 回复 2019-12-06
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

还有另一种解决方案,您可以使用字符串格式设置(类似于我猜的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)

没有精度


您需要27129.600000加仑水来填充该池。


精度8.2


您需要27129.60加仑的水来填充该池。


查看完整回答
反对 回复 2019-12-06
  • 3 回答
  • 0 关注
  • 563 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信