【问题标题】:python 2.7 function to convert temprature [closed]python 2.7函数转换温度[关闭]
【发布时间】:2015-07-06 22:43:05
【问题描述】:

我正在尝试编写一个将数字从摄氏度转换为华氏度的函数,我希望能够将结果打印到小数点后两位。

我的代码是:-

def Cel2Fah(temp): 

    temp = "28.0"

   return Cel2Fah

但我没有得到结果。任何帮助表示赞赏。

【问题讨论】:

  • 函数中哪里实现了转换公式?
  • 公式是 temp = "((28.0*9)/5)+32" 我试过了,但没有显示结果为空白
  • 看在上帝的份上,在编写更多代码之前,请遵循基本教程。

标签: python python-2.7


【解决方案1】:
celsius = float(input('Enter degree Celsius: '))

# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

【讨论】:

    【解决方案2】:

    您的函数从未真正进行计算。我认为您正在寻找这样的东西:

    def Cel2Fah(temp): 
        fah = temp * 9.0/5.0 + 32
    
        return fah
    

    您可以通过调用这样的函数以华氏度计算 28C:

    Cel2Fah(28)
    

    如果您想以 2 位小数打印华氏 29C,以下是您需要运行的所有代码:

    def Cel2Fah(temp): 
        fah = temp * 9.0/5.0 + 32
    
        return fah
    
    print "{0:.2f}".format(Cel2Fah(29.0))
    

    【讨论】:

    • 但问题是它没有返回两位小数的字符串,我用 float(Cel2Fah(29.0)) 尝试了 2 个位置
    • @RiteshSingh 您可以使用格式函数将其转换为具有 2 位小数的字符串:"{0:.2f}".format(Cel2Fah(29.0))
    • 它仍然无法正常工作,我也尝试过
    • @RiteshSingh 那么结果如何?
    • 可以转换温度但不显示结果小数点后两位