Python成绩计算器代码求助:百分比无法保留两位小数
Python成绩计算器:百分比无法正确保留两位小数的问题
我在Replit学习Python几周,现在写了一个成绩计算器程序,要求输入考试名称、满分和个人得分,输出保留两位小数的百分比成绩和对应等级。代码能运行,但百分比无法正确保留两位小数。以下是我的代码:
#intro print("\033[31m" + "-----------------------" + "\033[0m") print("Exam Grade Calculator📑") print("\033[31m" + "-----------------------" + "\033[0m") print() #main name_of_exam = input("What is the name of your exam?: ") max_score = int(input("What was the maximum score?: ")) score = int(input("What was your score?: ")) print() result = score / max_score percent = round(result * 100, 2) if percent >= 90: grade = "A+" print("You got", percent, "which is a", grade) elif percent >= 80 and percent < 90: grade = "A-" print("You got", percent, "which is a", grade) elif percent >= 70 and percent < 80: grade = "B" print("You got", percent, "which is a", grade) elif percent >= 60 and percent < 70: grade = "C" print("You got", percent, "which is a", grade) elif percent >= 50 and percent < 60: grade = "D" print("You got", percent, "which is a", grade) else: grade = "F" print("You got", percent, "which is a", grade) #outro print() print("\033[31m" + "-----------------------" + "\033[0m"
我尝试过修改百分比计算部分:
result = score / max_score percent = result * 100 round(percent, 2)
也调换过计算和round的顺序,但问题依旧。
问题分析与修正方案
round函数未赋值的错误
你第二次尝试的代码中,round(percent, 2)仅计算了结果,但没有将其赋值回percent变量,所以原变量数值未发生改变。正确写法应为percent = round(result * 100, 2),但这只能解决四舍五入问题,无法强制显示两位小数(例如80.0会被打印为80.0而非80.00)。核心问题:输出未格式化
Python打印float类型时会自动省略末尾的零,要强制保留两位小数,需使用字符串格式化,而非仅依赖round函数。
修正后的完整代码
#intro print("\033[31m" + "-----------------------" + "\033[0m") print("Exam Grade Calculator📑") print("\033[31m" + "-----------------------" + "\033[0m") print() #main name_of_exam = input("What is the name of your exam?: ") max_score = int(input("What was the maximum score?: ")) score = int(input("What was your score?: ")) print() result = score / max_score percent = result * 100 # 简化条件判断逻辑 if percent >= 90: grade = "A+" elif percent >= 80: grade = "A-" elif percent >= 70: grade = "B" elif percent >= 60: grade = "C" elif percent >= 50: grade = "D" else: grade = "F" # 使用f-string格式化输出,强制保留两位小数 print(f"You got {percent:.2f}%, which is a {grade}") #outro print() print("\033[31m" + "-----------------------" + "\033[0m")
关键修改说明
- 用
{percent:.2f}在格式化字符串中完成四舍五入并强制显示两位小数,确保所有结果都以两位小数形式输出(如80变为80.00,85.5变为85.50)。 - 简化了条件判断,去掉了冗余的
and percent < X,因为前面的条件已排除更高区间的情况。 - 修复了原代码末尾
print语句缺少闭合括号的语法错误。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

