课程及格所需分数计算器数学逻辑Bug排查求助
修复期末所需成绩计算的数学逻辑错误
问题根源
你的计算公式完全不符合加权成绩的计算逻辑,导致输出结果严重偏离预期。正确的加权成绩计算逻辑是:
总评成绩 = 当前成绩 × (1 - 期末权重占比) + 期末成绩 × 期末权重占比
从这个公式反推期末所需成绩,整理后得到正确的计算公式:期末成绩 = (目标总评 × 100 - 当前成绩 × (100 - 期末权重)) / 期末权重
修正后的代码
替换错误的计算逻辑,同时新增非数字输入的异常处理,避免程序崩溃:
var goal by remember { mutableStateOf("") } var currentGrade by remember { mutableStateOf("") } var finalWeight by remember { mutableStateOf("") } var finalGradeNeeded by remember { mutableStateOf("") } if (goal.isNotEmpty() && currentGrade.isNotEmpty() && finalWeight.isNotEmpty()) { val goalDouble = goal.toDoubleOrNull() val currentDouble = currentGrade.toDoubleOrNull() val weightDouble = finalWeight.toDoubleOrNull() when { weightDouble == null || weightDouble == 0.0 -> { finalGradeNeeded = "Error: Invalid weight" } goalDouble == null || currentDouble == null -> { finalGradeNeeded = "Error: Invalid number input" } else -> { val required = (goalDouble * 100 - currentDouble * (100 - weightDouble)) / weightDouble finalGradeNeeded = String.format("%.1f", required) } } } Text( text = "Your final grade needs to be: $finalGradeNeeded%", fontWeight = FontWeight.Bold, fontSize = 15.sp )
验证示例
输入当前成绩50、目标成绩50、期末权重50时,代入公式计算:(50×100 - 50×(100-50)) /50 = (5000 -2500)/50 = 2500/50 =50,输出结果为50.0%,符合预期。
内容的提问来源于stack exchange,提问作者notryan
相关产品推荐
相关产品推荐

