【问题标题】:Temp conversion - output issues临时转换 - 输出问题
【发布时间】:2021-09-04 16:42:47
【问题描述】:

我有 4 行必需的代码,我需要在适当的行中添加: 编写函数以将华氏温度转换为摄氏温度,反之亦然。

为什么我要发布我的问题: 最初的输出“none”问题解决了现在得到错误的数字。

我相信我理解的事情正在发生: 我正在尝试打印一个没有返回语句的函数。因此,当我在函数 celsius_to_fahrenheit(100)) 上使用 print 时,它“正确”运行,但由于需要 4 行,我必须运行 print(celsius_to_fahrenheit(100)) 行。

我在添加问题之前使用过的资源: https://beginnersbook.com/2019/05/python-program-to-convert-celsius-to-fahrenheit-and-vice-versa/

https://en.wikipedia.org/wiki/Fahrenheit

我得到了什么: 37.77777777777778

我的期望: 摄氏度到华氏度(100) 212.0

必需的代码:我删除了多余的间距

    def fahrenheit_to_celsius(temp):
    def celsius_to_fahrenheit(temp):
    if __name__ == "__main__":
        print(celsius_to_fahrenheit(100))

代码解析:

def fahrenheit_to_celsius(temp):
    temp = (temp -32)* 5/9
    return(temp)
def celsius_to_fahrenheit(temp):
    temp = (temp *9/5)+32
    return(temp)
if __name__ == "__main__":
    print(celsius_to_fahrenheit(100))

【问题讨论】:

  • 你为什么不从函数中返回任何东西?
  • @DiptoMondal 我不知道这是我需要做的。这是否意味着如果我在打印之前添加一个“return(temp)”它应该可以解决我的问题?我会开始在代码中处理它,如果可行,我会回复你!
  • 请不要用答案代替您的问题。这不是本网站的运作方式。
  • 并且不要在你的问题标题中使用 SOLVED 。这是一个古老的论坛技巧;在这里,我们通过单击正确答案旁边的复选标记来接受解决问题的答案。
  • @DiptoMondal 我在程序中用 return 进行了编辑。那是缺失的部分;我还必须切换第 2 行和第 5 行(带有转换公式的行),并根据需要完全修复程序。感谢您的帮助!我将更多地研究何时/如何使用内置功能“return”以备将来使用!我确实留下了赞成票,但目前我没有足够的声誉来计算它。

标签: python data-conversion temperature


【解决方案1】:

这就是你应该如何从 python 函数返回

def fahrenheit_to_celsius(temp):
    temp = (temp *9/5)+32
    return temp
def celsius_to_fahrenheit(temp):
    temp = (temp -32)* 5/9
    return temp
if __name__ == "__main__":
    print(celsius_to_fahrenheit(100))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多