31

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

这是到目前为止的程序:

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

我该怎么办?

4

3 回答 3

46

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

这应该可以正常工作:(注意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.
于 2013-06-28T13:23:01.367 回答
4

还有一种解决方案,您可以使用字符串格式化(我猜类似于 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-05-17T19:00:01.507 回答
3

使用 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-10-03T00:50:39.400 回答