Python温度判断程序输入小数时报错的原因咨询
问题原因及解决办法
报错根源
你代码里的int(input("What temperature are you?"))是核心问题:int()函数只能转换纯整数格式的字符串(比如"37"),当输入带小数点的内容(比如"37.888888")时,它无法处理这类字符串,直接抛出ValueError导致程序崩溃。
修正方案
方案1:支持小数输入
把int()替换成float(),这样既能接收整数,也能处理小数输入:
temperature = float(input("What temperature are you?")) if temperature >= 37 and temperature < 50: print("your temperature is healthy, as it is", "%.2f" % temperature) else: print("You said your temperature was", "%.2f" % temperature, "You are unhealthy")
方案2:添加小数取整逻辑
如果需要对输入的小数做取整处理(比如保留两位小数),可以用round()函数:
# 保留两位小数 temperature = round(float(input("What temperature are you?")), 2) if temperature >= 37 and temperature < 50: print("your temperature is healthy, as it is", "%.2f" % temperature) else: print("You said your temperature was", "%.2f" % temperature, "You are unhealthy")
如果需要向上/向下取整,要先导入math模块:
import math # 向上取整 temperature = math.ceil(float(input("What temperature are you?"))) # 或者向下取整 temperature = math.floor(float(input("What temperature are you?"))) if temperature >= 37 and temperature < 50: print("your temperature is healthy, as it is", temperature) else: print("You said your temperature was", temperature, "You are unhealthy")
内容的提问来源于stack exchange,提问作者VincentOfTheHighlands
相关产品推荐
相关产品推荐

