我在这段代码的输出中得到了很多小数(华氏到摄氏度转换器)。
我的代码目前看起来是这样的:
def main():
printC(formeln(typeHere()))
def typeHere():
global Fahrenheit
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(c):
Celsius = (Fahrenheit - 32.00) * 5.00/9.00
return Celsius
def printC(answer):
answer = str(answer)
print "\nYour Celsius value is " + answer + " C.\n"
main()
我的问题是,如何让程序把每个答案四舍五入到小数点后2位?
可以使用python“%”的字符串格式化操作符。
“%。“2f”表示小数点后2位。
def typeHere():
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(Fahrenheit):
Celsius = (Fahrenheit - 32.0) * 5.0/9.0
return Celsius
def printC(answer):
print "\nYour Celsius value is %.2f C.\n" % answer
def main():
printC(formeln(typeHere()))
main()
http://docs.python.org/2/library/stdtypes.html#string-formatting
可以使用python“%”的字符串格式化操作符。
“%。“2f”表示小数点后2位。
def typeHere():
try:
Fahrenheit = int(raw_input("Hi! Enter Fahrenheit value, and get it in Celsius!\n"))
except ValueError:
print "\nYour insertion was not a digit!"
print "We've put your Fahrenheit value to 50!"
Fahrenheit = 50
return Fahrenheit
def formeln(Fahrenheit):
Celsius = (Fahrenheit - 32.0) * 5.0/9.0
return Celsius
def printC(answer):
print "\nYour Celsius value is %.2f C.\n" % answer
def main():
printC(formeln(typeHere()))
main()
http://docs.python.org/2/library/stdtypes.html#string-formatting