我如何获得浮动结果? (蟒蛇)

时间:2016-04-30 15:24:57

标签: python-3.x

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

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)))

2 个答案:

答案 0 :(得分:0)

print("You will need %.2f litres of paint." % result)
  • %d - 格式编号为整数
  • %f - 格式编号为float,小数点后的位数无限制
  • %。xf - x小数点后的位数(例如%.2f)

答案 1 :(得分: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)