对于一堂课,我要编写一个程序,将华氏温度转换为摄氏温度,反之亦然。结果应四舍五入到小数点后第一位。我已经以多种方式尝试了“回合”功能,但没有成功。
temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))
if unit=="c" or unit == "C":
degC=(temp)
temp= (1.8*temp)+32
print(str(temp) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
if unit=="f" or unit == "F":
degF=(temp)
temp= (temp-32)/1.8
print(str(temp)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")
答案 0 :(得分:1)
您可以使用round(number, 1)
内置功能!
例如:
>>> round(45.32345, 1)
45.3
在您的情况下:
temp=float(input("Enter a temperature value to convert: "))
unit=str(input("Convert to Fahrenheit or Celsius? Enter f or c: "))
if unit=="c" or unit == "C":
degC=(temp)
temp= (1.8*temp)+32
print(str(round(temp), 1) + " degrees fahrenheit = " + str(degC) + " degrees Celsius. ")
el*emphasized text*if unit=="f" or unit == "F":
degF=(temp)
temp= (temp-32)/1.8
print(str(round(temp), 1)+ " degrees celsius = " + str(degF) + " degrees Fahrenheit. ")
else:
print("you did not enter an f or c. Goodbye ")
python实际执行的操作类似于:
def truncate(n, decimals=0):
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier
您可以阅读有关python-rounding
的更多信息希望这会有所帮助!
答案 1 :(得分:1)
python的一个不错的功能是python shell可以让您探索不了解的所有内容。
$ python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print( round(3.1415,3), round(3.1415,2), round(3.1415,1), round(3.1415,0))
3.142 3.14 3.1 3.0
>>> help(round)
<various help is printed>
通常,您可以测试很多代码,以查看您的理解是否与实际行为相符。从我的示例中,我认为您可以看到round()的行为,也许您真正的问题在其他地方。