JavaScript平均分计算函数输出结果异常求助:新手开发者问题排查
Hey there! Let's troubleshoot why your grade calculation function isn't outputting the correct results. I've spotted two key issues in your code—let's break them down and fix them step by step:
1. Prompt Returns Strings, Not Numbers
The prompt() function gives you user input as a string, not a numerical value. When you run maths + physics + chemistry, you're actually gluing strings together instead of adding numbers. For example, if you enter 70, 70, 70, you'll get "707070" instead of 210, which makes the average calculation totally wrong.
Fix: Convert Inputs to Numbers
Wrap each prompt() call with Number() (or parseFloat()) to turn the string input into a number:
let maths = Number(prompt('Please type grade in Math')); let physics = Number(prompt('Please type grade in Physics')); let chemistry = Number(prompt('Please type grade in Chemistry'));
2. Incorrect Condition Boundaries
Your current logic doesn't handle the 70 threshold right. According to your requirement:
- <70 → Grade C
- 70 (exclusive) to 90 (exclusive) → Grade B
- ≥90 → Grade A
But your else if (grade > 70 && grade < 90) means an average of exactly 70 will fall into the else block and output Grade A, which isn't what you want.
Fix: Adjust Condition Logic
If you meant that 70 and above (up to 90 exclusive) should be Grade B (a more common grading rule), update the condition to:
if (grade < 70) { document.write('Your grade is: C'); } else if (grade >= 70 && grade < 90) { document.write('Your grade is: B'); } else { document.write('Your grade is: A'); }
If you strictly want to exclude 70 from Grade B (so exactly 70 stays as Grade C), keep the grade > 70 check—just be aware that this edge case will now output C instead of A.
Full Corrected Code
Here's the complete fixed code with both issues addressed:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Grade Calculator</title> <script> function calculateGrade() { // Convert input strings to numbers let maths = Number(prompt('Please type grade in Math')); let physics = Number(prompt('Please type grade in Physics')); let chemistry = Number(prompt('Please type grade in Chemistry')); // Calculate average let average = (maths + physics + chemistry) / 3; // Determine grade based on requirements if (average < 70) { document.write('Your grade is: C'); } else if (average >= 70 && average < 90) { document.write('Your grade is: B'); } else { document.write('Your grade is: A'); } } calculateGrade(); </script> </head> <body> </body> </html>
Quick Test Cases
- Inputs: 60, 60, 60 → Average 60 → Output:
Your grade is: C - Inputs: 80, 80, 80 → Average 80 → Output:
Your grade is: B - Inputs: 90, 90, 90 → Average 90 → Output:
Your grade is: A - Inputs: 70, 70, 70 → Average 70 → Output:
Your grade is: B(with the adjusted condition)
内容的提问来源于stack exchange,提问作者Mark

