多浮点数值范围校验问题:科目成绩有效性校验代码异常排查
问题分析
原代码的核心错误在于用range(0,11)判断成绩合法性。range(0,11)仅生成0到10的整数序列,但合法成绩允许0-10之间的浮点数(如7.25、5.1),因此所有非整数的合法成绩都会被误判为无效,导致输入7.25时输出NOK。
修正方案
根据需求(成绩范围0-10,步长0.1,支持5.25、5.1这类数值),提供两种适配方案:
方案1:允许0-10之间的任意浮点数(匹配用户示例)
如果仅要求成绩落在0到10的区间内,无需严格限制小数位数,可直接校验区间:
def Task_22(): try: mathematics = float(input("Input mathematics score: ")) literature = float(input("Input literature score: ")) english = float(input("Input english score: ")) # 校验每个成绩是否在0-10之间(包含边界) if all(0 <= score <= 10 for score in [mathematics, literature, english]): print("OK") else: print("NOK") except ValueError: # 处理输入非数字的非法情况 print("NOK")
方案2:严格遵循步长0.1(仅允许一位小数)
如果需要严格限制成绩为0.0、0.1、0.2…10.0这类一位小数,可通过验证“成绩乘以10后为整数”实现(处理浮点数精度问题需用round):
def Task_22(): try: mathematics = float(input("Input mathematics score: ")) literature = float(input("Input literature score: ")) english = float(input("Input english score: ")) def is_valid(score): # 先判断区间,再验证步长符合要求 return 0 <= score <= 10 and round(score * 10) == score * 10 if all(is_valid(score) for score in [mathematics, literature, english]): print("OK") else: print("NOK") except ValueError: print("NOK")
测试验证
输入示例内容:
Input mathematics score: 2 Input literature score: 5 Input english score: 7.25
- 方案1会输出
OK,完全匹配用户预期; - 方案2会输出
NOK(7.25是两位小数,不符合严格步长要求)。
内容的提问来源于stack exchange,提问作者Lĩnh Trần
相关产品推荐
相关产品推荐

