Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将英寸转换为英尺_Python_Floating Point_Rounding_Arithmetic Expressions - Fatal编程技术网

Python:将英寸转换为英尺

Python:将英寸转换为英尺,python,floating-point,rounding,arithmetic-expressions,Python,Floating Point,Rounding,Arithmetic Expressions,我想如果我让数字浮动,它会给我一个带小数点的数字 height = 65.0 / 12.0 print height 当我在字符串中使用它时,我得到的是5,没有余数。比如说: print "He is %d tall." % height 如果要坚持使用%格式,请使用%g获取小数位: In [5]: print("He is %g tall." % height) He is 5.41667 tall. 您还可以定义小数位数,例如像这样的2位%.2f: 然而,Python的格式化方

我想如果我让数字浮动,它会给我一个带小数点的数字

height = 65.0 / 12.0
print height
当我在字符串中使用它时,我得到的是5,没有余数。比如说:

    print "He is %d tall." % height

如果要坚持使用%格式,请使用%g获取小数位:

In [5]: print("He is %g tall." % height)
He is 5.41667 tall.
您还可以定义小数位数,例如像这样的2位%.2f:

然而,Python的格式化方式是:

In [14]: print("He is {0:.2f} tall.".format(height))
He is 5.42 tall.
print "He is {0:.2f} tall.".format(height)
在这里您可以找到一个很好的概述:

编辑:

板球007是对的:OP使用的是蟒蛇2。因此,正确的语法应该是:

In [14]: print("He is {0:.2f} tall.".format(height))
He is 5.42 tall.
print "He is {0:.2f} tall.".format(height)

在[3]中:print 65.0/12.0 5.41667对我来说就像预期的那样工作。我实际上是在字符串中使用它,带有%d,但它打印的所有内容都是字符串中的5。我像上面那样做了,而且成功了。所以这看起来像个愚蠢的问题,…%d代表整数。你还指望什么?!OP正在使用Python 2