python - 我需要知道如何让我的函数返回 float 。我对 float 标签的放置位置感到困惑

标签 python python-2.7 floating-point

我目前正在学习一个 Python 教程,该教程要求我创建一个随机函数并以 10 种不同的方式运行它。我一直在想如何让它真正使用 float 。我认为我应该发布整个内容并指出我试图让 float 发挥作用的地方

def volume (length, width, height):
    print "the object is %d cm long, %d cm wide, and %d cm high" % (length, width, height),
    total_volume = float(length * width * height)
    print "The total volumeis %d cm3" % total_volume


print "Direct input:"
volume (10, 20, 30)

print "direct input variables:"
length = (10)
width = (20)
height = (30)
volume (length, width, height)

print "direct input variables and math"
volume (length + 10, width +20, height +30)

print "direct input math"
volume (10 + 10, 20 +20, 30 + 30)


print "user input with int(raw_input)"
length2 = int(raw_input("what is the length? "))
width2 = int(raw_input("what is the width? "))
height2 = int(raw_input("what is the height? "))
volume (length2, width2, height2)

#here is the first problem
print "user input with float(raw_input)"
length3 = float(raw_input("what is the length? "))
width3 = float (raw_input("what is the width? "))
height3 = float (raw_input("what is the height? "))
volume (length3, width3, height3)

#Doesn't work here either`
print "float(raw_input) + variables"
print "the base oject size is 10 * 10 * 10"
print "why is this important? IT ISN'T!!!!!"
print "However, eventually I will make one that calculates the increase in volume"
length4 = length + float(raw_input("How much length are you adding? "))
width4 = width + float(raw_input("How much width are you adding? "))
height4 = height + float(raw_input("How much height are you adding? "))
volume (length4, width4, height4)

这两部分只是拒绝返回 float 。这是我迄今为止尝试过的。

我尝试在调用函数变量时添加 float ,如下所示

体积 float (长度4,宽度4,高度4)

我尝试将 float 添加到函数的实际定义部分,如下所示

def体积 float (长,宽,高):

如您所见,我将 float 放置在函数的实际数学部分中,但没有任何效果。

一定可以做到这一点。我希望有更有知识的人可以指点迷津,但我没有主意了

最佳答案

您的数学没有任何问题,您只是使用 %d 将结果打印为整数。如果您改用 %f,您应该会看到正确的结果:

print "The total volume is %f cm3" % total_volume
# Here ---------------------^

关于python - 我需要知道如何让我的函数返回 float 。我对 float 标签的放置位置感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784966/

相关文章:

python - 如何从噪声背景中提取白色 Blob ?

Python 3.5 BytesIO 错误

python - 重采样错误 : cannot reindex a non-unique index with a method or limit

python - 如何使用 pyspark 为非 pairwiseRDDs 正确 groupByKey

swift - Swift 中的 Double vs Float80 速度

python - 在 seaborn factorplot 中绘制虚线

python - 使用 Python 的非阻塞 SQL 执行

javascript - Azure 存储 SAS token 在本地主机上工作,但部署在 Azure Kubernetes 上时不起作用

mysql - mysql中的float精度问题

math - 为什么浮点运算在添加小数时不能给出准确的结果?