如何避免python四舍五入?

时间:2016-09-04 16:01:13

标签: python-2.7 powershell-v2.0

我对python&总体。所以我写这段代码作为一些实践的一部分,涉及制作一个转换器,当代码通过PowerShell运行时,转换器可以将重量和高度的输入值分别从kg转换为lbs和英寸到英尺。

使用第一段代码,输出结果四舍五入,我想知道为什么?此外,如何避免这种情况。

但是,使用第二段代码时,输​​出不会四舍五入。为什么呢?

    print "This is my personal converter."
height = int(raw_input("what is your height in inches? "))
weight = int(raw_input("what is your wieght in kilograms? "))
kg_to_lbs_rate = 2.20462
inches_to_feet_rate = 0.0833333

print "Since your height in inches is equal to %d, then your height in feet should equal to %d" % (height, height * inches_to_feet_rate),"feet"
print "Since your weight in kilograms is equal to  %d, then your weight in lbs should equal to %d" % (weight, weight * kg_to_lbs_rate),"lbs"
    print "This is my personal converter."
height = int(raw_input("what is your height in inches? "))
weight = int(raw_input("what is your wieght in kilograms? "))
kg_to_lbs_rate = 2.20462
inches_to_feet_rate = 0.0833333

print "Since your height in inches is equal to %d, then your height in feet should equal to " % height, height * inches_to_feet_rate,"feet"
print "Since your weight in kilograms is equal to  %d, then your weight in lbs should equal to" % weight, weight * kg_to_lbs_rate,"lbs"

Here's the output of both the codes when run in PowerShell

2 个答案:

答案 0 :(得分:0)

在第一个代码中,你指定%d从结果中仅提取整数部分。 在第二个代码中没有特定的数据类型,因此它打印出准确的答案。

答案 1 :(得分:0)

@ayhan是正确的,当您使用%d时,它会在您显示时四舍五入。请参阅文档here。如果要显示浮动,可以使用%f

print 'test: %f', 3.43

然而,通常首选使用str.format

print 'test: {}'.format(3.43)