gpt4 book ai didi

python - 无法连接 'str' 和 'float' 对象?

转载 作者:IT老高 更新时间:2023-10-28 22:12:03 26 4
gpt4 key购买 nike

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

这是目前为止的程序:

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

我该怎么办?

最佳答案

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

这应该可以正常工作:(注意乘法结果的 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.

关于python - 无法连接 'str' 和 'float' 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com