Reputation: 3
I am a newbie in studying Javascript, why is my function not viewing the correct answer? Can you help me understand what is the problem with it. Because if the computation is < 70 it should be C, etc...
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function type() {
let maths = prompt('Please type grade in Math');
let physics = prompt('Please type grade in Physics');
let chemistry = prompt('Please type grade Chemistry');
let grade = (maths + physics + chemistry)/3;
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');
}
}
type();
</script>
</head>
<body>
</body>
</html>
Upvotes: 1
Views: 230
Reputation: 5828
The issue is that prompt returns a string, not a number. The below example converts it to a number using parseFloat so that you can calculate the average.
It would be better to use number inputs, which allow you to set minimum and maximum allowed values and handle some validation for you.
Also, not sure it makes sense that if I enter 0 for each class I still get a C.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function type() {
let maths = parseFloat(prompt('Please type grade in Math'));
let physics = parseFloat(prompt('Please type grade in Physics'));
let chemistry = parseFloat(prompt('Please type grade Chemistry'));
let grade = (maths + physics + chemistry)/3;
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');
}
}
type();
</script>
</head>
<body>
</body>
</html>
Upvotes: 1