【问题标题】:What's wrong with my code to convert farenheight to Celsius?我将华氏温度转换为摄氏温度的代码有什么问题?
【发布时间】:2017-09-25 10:42:51
【问题描述】:
#Programme to covert Farenheight to Celcius
F=input("Enter Value:")

F=((F-32)/9)*5
       print("The temperature is ",F,"Degrees Celcius")

当我尝试运行它时,它显示 TypeError: unsupported operand type(s) for -: 'str' and 'int'

【问题讨论】:

  • input 返回一个 str 您需要将其转换为浮点数才能使其工作
  • F = int(input('..'))
  • 有道理,谢谢。我现在把它写成这样 F=int(input("Enter Value:") Celcius=((F-32)/9)*5 print("The temperature is ",Celcius,"Degrees Celsius") 现在在 celsius 'invalid syntax' 下的计算行上说?
  • 您错过了 cmets 中代码的 int() 的右括号
  • 好的,现在可以了。谢谢大家

标签: python macos converter


【解决方案1】:

将您输入的类型转换为 int

F=int(input("Enter Value:"))

并强制除法返回一个浮点数。 在最顶部添加这个

from __future__ import division

【讨论】:

    【解决方案2】:
    `F=((float(F)-32)/9)*5`
    

    或者

    F=float(input('Enter value'))
    [...]`
    

    输入返回字符串,你必须将它们更改为int或float。

    【讨论】:

      【解决方案3】:

      您需要使用浮点数:

      #Programme to covert Farenheight to Celcius
      F = float(input("Enter Value:"))
      
      F = ((F-32.0) / 9.0) * 5.0
      print("The temperature is {:.1f} Degrees Celcius".format(F))
      

      给你:

      Enter Value:33
      The temperature is 0.6 Degrees Celcius
      

      {:.1f} 告诉它将F 浮点结果格式化为字符串到小数点后一位。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-08
        • 2021-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-19
        • 1970-01-01
        相关资源
        最近更新 更多