如何避免 python 四舍五入?

How to avoid python from rounding off the numbers?

我对 python 和整体来说真的很陌生。因此,我将这段代码作为一些实践的一部分进行编写,该实践涉及制作一个转换器,当代码为 运行 通过 PowerShell 时,该转换器可以将重量和身高的输入值分别从千克转换为磅,将英寸转换为英尺。

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

但是,对于第二段代码,输出没有四舍五入。为什么?

    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

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

@ayhan 说的对,显示的时候四舍五入了,因为你用的是%d。请参阅文档 here。如果你想显示一个浮点数,你可以使用 %f:

print 'test: %f', 3.43

但是通常首选使用 str.format

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