在python中打印浮点
如何打印值为floting数的变量 例如在python中打印浮点,python,variables,printing,point,floating,Python,Variables,Printing,Point,Floating,如何打印值为floting数的变量 例如 为什么返回值是1而不是1.75,我如何更改它?您应该使用%f: my_height = 1.75 #meters >>> print "I'm %f meters tall." % my_height I'm 1.750000 meters tall. 要指定特定精度,请按以下方式执行: my_height = 1.75 #meters >>> print "I'm %.2f meters tall." % my_h
为什么返回值是1而不是1.75,我如何更改它?您应该使用
%f
:
my_height = 1.75 #meters
>>> print "I'm %f meters tall." % my_height
I'm 1.750000 meters tall.
要指定特定精度,请按以下方式执行:
my_height = 1.75 #meters
>>> print "I'm %.2f meters tall." % my_height #the 2 denoting two figures after decimal point
I'm 1.75 meters tall.
因为在字符串格式中,就像在C中一样,
%d
给出一个整数
要修复它,您需要使用%f
而不是%d
:
print "I'm %f meters tall." % my_height
# Outputs "I'm 1.75 meters tall."
您正在使用%d显示浮点数。您可以尝试以下方法来精确显示浮点数。Python3及以上版本首选方法2 方法1:
打印“我是%.2f米高。”%my_身高
方法2:
打印“我{.2f}米高。”.format(我的身高)
您使用的字符串格式参数%d
用于(十进制)整数。改用%f
。仅仅因为它可以用一个字母固定,并不意味着它是一个打字错误。这本不应该关闭的。这是一个真正的问题,可以复制?对是打字错误吗?不,是因为还不知道相关的编程信息。我想说这完全是关于这个主题的,应该重新打开。谢谢,我刚刚开始学习python,它是我的第一语言,所以我有点lost@user3629046,没问题,很高兴我能帮忙。
print "I'm %f meters tall." % my_height
# Outputs "I'm 1.75 meters tall."