JavaScript样本测试分数计算函数的问题排查与修正
scoreTest Function for Percentage Calculation Hey there! Let's get your score calculation sorted out—your current logic has the formula backwards, which is why some test cases are failing.
The Problem with Your Current Code
Your line percent = (correct*questions); is multiplying correct answers by total questions, which gives an unrelated large number instead of a percentage. To calculate the percentage of correct answers, you need to follow the right mathematical steps:
- Divide the number of correct answers by the total number of questions
- Multiply that result by 100 to convert it to a percentage
- Ensure you return an integer (since all your test cases expect whole numbers)
Corrected Code
Here's the fixed version of your function:
function scoreTest(correct, questions) { var percent; // Only change code below this line percent = Math.round((correct / questions) * 100); // Only change code above this line return percent; }
Why This Works
Let's verify against your test cases to confirm:
scoreTest(47,50):(47/50)*100 = 94→ returns 94 ✅scoreTest(16,20):(16/20)*100 = 80→ returns 80 ✅scoreTest(97,100):(97/100)*100 = 97→ returns 97 ✅scoreTest(1,50):(1/50)*100 = 2→ returns 2 ✅
We use Math.round() here to handle edge cases where division might result in a decimal (like 3 correct out of 7 questions would round to 43 instead of leaving you with 42.85...). If you're guaranteed all test cases will result in whole numbers, you could also use (correct * 100) / questions which works just as well.
内容的提问来源于stack exchange,提问作者PreYVin

