2013-05-13 72 views
0

我刚开始学习python,目前正在编写一个脚本,将摄氏温度转化为华氏温度,反之亦然。我已经完成了主要部分,但现在我希望能够让用户设置输出中显示的小数位数......第一个函数包含我失败的尝试,第二个函数设置为2位小数。用户设置的函数中的可变小数点限制?

def convert_f_to_c(t,xx): 
c = (t - 32) * (5.0/9) 
print "%.%f" % (c, xx) 

def convert_c_to_f(t): 
    f = 1.8 * t + 32 
    print "%.2f" % f  


print "Number of decimal places?" 
dec = raw_input(">") 

print "(c) Celsius >>> Ferenheit\n(f) Ferenheit >>> Celcius" 
option = raw_input(">") 

if option == 'c': 
    cel = int(raw_input("Temperature in Celcius?")) 
    convert_c_to_f(cel) 

else: 
    fer = int(raw_input("Temperature in Ferenheit?")) 
    convert_f_to_c(fer,dec) 

回答

5
num_dec = int(raw_input("Num Decimal Places?") 
print "%0.*f"%(num_dec,3.145678923678) 

在%格式字符串,你可以使用一个*此功能

AFAIK存在'{}'.Format方法没有equivelent方法

>>> import math 
>>> print "%0.*f"%(3,math.pi) 
3.142 
>>> print "%0.*f"%(13,math.pi) 
3.1415926535898 
>>> 
+0

“%0. * f”%(13,math.pi)的操作对我来说有点令人困惑,因为*是在%之前定义的......任何原因为什么?或者只是约定。 在我的背景下,成为 '打印 “0%* F” %(XX,C)' 和它的作品! 谢谢 – AllTheTime1111 2013-05-13 23:11:35

+0

@ AllTheTime1111:阅读[docs](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations)。我同意这不是最简单的理解,但它在那里。特别注意关于精度的部分(编号列表中的第5项解释转换说明符)。 – 2013-05-13 23:16:34

+2

''{0:。{1} f}'。format(math.pi,3)'是新方法 – Eric 2013-05-13 23:18:37

1

这工作:

>>> fp=12.3456789 
>>> for prec in (2,3,4,5,6): 
... print '{:.{}f}'.format(fp,prec) 
... 
12.35 
12.346 
12.3457 
12.34568 
12.345679 

这个例子也一样:

>>> w=10 
>>> for prec in (2,3,4,5,6): 
... print '{:{}.{}f}'.format(fp,w,prec) 
... 
    12.35 
    12.346 
    12.3457 
    12.34568 
12.345679 

甚至:

>>> align='^' 
>>> for prec in (1,2,3,4,5,6,7,8,9): 
...    print '{:{}{}.{}f}'.format(fp,align,15,prec) 
...  
     12.3       
     12.35      
    12.346      
    12.3457     
   12.34568     
   12.345679    
  12.3456789    
  12.34567890   
 12.345678900 

它会自动字段选择毛发过多之前,您可以使用手动也和周围交换领域:

>>> for prec in (2,3,4,5,6): 
... print '{2:{0}.{1}f}'.format(w,prec,fp) 
... 
    12.35 
    12.346 
    12.3457 
    12.34568 
12.345679 

最好的文档是在PEP 3101