2016-03-03 50 views
1

我目前正在通过一个蟒蛇教程,要求我创建一个随机函数并运行它10种不同的方式。我被困在如何真正让它使用浮动。我想我应该张贴了整个事情,只是指出在那里我试图让漂浮工作我需要知道如何让我的函数返回浮动。我很困惑我在哪里把浮标

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) 

这两部分简单地拒绝返回浮动。这是我到目前为止所尝试的。

我尝试添加该函数变量调用时浮,如下

量浮动(length4,width4,宽度4)

我试图浮动添加到函数的实际定义部分如下

DEF体积浮子(长度,宽度,高度):

,你可以看到,我有浮动放置在该函数的实际的数学部分,没有效果。

它必须是可能的,使这项工作。我希望有人更有知识可以指出方向,我不知道

+0

使用'return'语句和你想要返回的任何值(变量):'return total_volume'。 – Evert

+0

为了记录:Python不是C语言或类似语言:不需要声明类型(但可以[提示类型](https://docs.python.org/3/library/typing.html) Python 3.5)。 – Evert

+0

并不是说你也不会有后果:在函数中将'total_volume'强制转换为浮点数,然后使用'%d'(整数)说明符将其打印出来。 – Evert

回答

1

你的数学没有错,你只是使用%d作为整数打印结果。如果您使用%f相反,你应该可以看到正确的结果:当你想浮动,而不是整数

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

谢谢。可能不会有这样的想法。我想要更多关注格式化程序 – Cthulhu

1

使用%f而不是%d

此外,您可以更多地使用"%0.2f"来格式化字符串,其中2是您希望的小数位数。

>>> x = 1.2342345 
>>> print "%0.2f" % x 
1.23 
相关问题