Python 2.7 为什么我通过打印%f获得此输出-Python 2.7
快速问题:为什么在这个脚本的输出中小数点后会有很多零(“total”变量的值)?(我知道如何处理它,并通过四处走动获得特定的爆发,但我很好奇为什么这个iutput看起来像这样) 脚本:Python 2.7 为什么我通过打印%f获得此输出-Python 2.7,python-2.7,Python 2.7,快速问题:为什么在这个脚本的输出中小数点后会有很多零(“total”变量的值)?(我知道如何处理它,并通过四处走动获得特定的爆发,但我很好奇为什么这个iutput看起来像这样) 脚本: prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3, } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, }
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
print
total = 0
for iteration in prices:
total = total+ prices[iteration] * stock[iteration]
print "total price: %f"%total
输出:
banana
price: 4
stock: 6
apple
price: 2
stock: 0
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
total price: 117.000000 #********* why so many zeros?
因为这是
%f
格式化程序的默认小数位数
添加精度说明符;例如,如果只想显示2位小数,请使用%.2f
:
print "total price: %.2f" % total
最后一行输出就变成了
total price: 117.00
格式规范中后跟数字的
表示精度说明符。见:
转换说明符包含两个或多个字符,并具有以下组件,这些组件必须按此顺序出现:
[……]
”。
(点),后跟精度。[……]f
的默认值记录在脚注#3中:
精度决定小数点后的位数,默认为6
如果不需要零,则必须用%d或%i替换%f;如果需要1零,则可以用%s替换:
>>> print "total price: %d"%total
total price: 117
>>> print "total price: %s"%total
total price: 117.0
>>> print "total price: %f"%total # Like you did
total price: 117.000000
多谢各位!我已经阅读了这篇文档,但显然不理解这一点。谢谢你抽出时间,但这并没有回答我的问题,我已经知道了(就像我在帖子中写道的:“我知道如何处理它,并通过走来走去获得特定的爆发,但我很好奇为什么这个输出看起来像这样”)。