2016-04-30 131 views
0

正如你可以从下面的代码中看出的那样,我一直在试图获得一个浮点结果,但是每次我在数字中打拳击,它总是给我一个int。任何帮助,将不胜感激。如何获得浮动结果? (Python)

def wallArea(x, y): 
    height = float(x) 
    width = float(y) 
    result = float(x*y) 
    return float(result) 

def obsturctionArea(x, y): 
    height = float(x) 
    width = float(y) 
    result = float(x*y) 
    return float(result) 

litre = float(12.0) 

#UserInput 
x=float(input("Please enter the height of your wall.")) 
y=float(input("Please enter the width of your wall.")) 
a=float(input("Please enter the height of the obtruction.")) 
b=float(input("Please enter the width of the obtruction.")) 
coats = float(input("How many coats of paint would you like?")) 

totalArea = float(wallArea(x, y)-obsturctionArea(a, b)) 
result = float(totalArea/litre*coats) 

print("You will need %d litres of paint." % (float(result))) 
+0

试试这个:http://stackoverflow.com/questions/1267869/我怎样才能在i中划分浮点运算? – Marco

+0

您可以定义高度和宽度,然后使用x和y作为结果......为什么?尝试使用宽度和高度。 – Shovalt

+0

哦,嘿,你用%d代表数字!你需要%f或%.2f,如果你想很好地显示 – Shovalt

回答

0
print("You will need %.2f litres of paint." % result) 
  • %d - 格式数作为整数
  • %的F - 的格式号作为浮动,小数点后的位数没有限制
  • %.xf - x个的小数点(例如%.2f)
0

改变该行之后的数字

print("You will need %d litres of paint." % (float(result))) 

print("You will need %f litres of paint." % (float(result))) 

因为%d示出了可变 的整数值,但是%F显示了浮之一。

你也可以指定在浮体部

例如位数:

x = 0.123456 
print("result = %.2f " % x 
# result = 0.12 
# %.2f shows only 2 digits in the float part 

也是另一个此言为您的代码: 变量(高度,宽度)有没有影响你的代码,因为它们没有在函数中使用。 也许你想保证您的变量 的浮动铸造所以如果这是你的意思,你必须改变你的函数代码:

def wallArea(x, y): 
    height = float(x) 
    width = float(y) 
    result = float(height*width) 
    return float(result) 

def obsturctionArea(x, y): 
    height = float(x) 
    width = float(y) 
    result = float(height*width) 
    return float(result) 
+0

感谢您的信息 - 将有助于未来! – naf