Skip to content
Advertisement

JavaScript is displaying an incorrect mathematical answer

I wrote this small script that would calculate a students GPA. I decided to test it midway and it appears as if the code messes up.

<!DOCTYPE html>
<html>
<head>
    <title>GPA Calculator</title>
</head>
<body>
    
    <input type="text" id="varA">
    <input type="text" id="varB">
    <input type="text" id="varC">
    <input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')"></input>
    <h1 id="testResult"></h1>
    <script>
            function addNumbers(elem1, elem2, elem3) {
            var a = document.getElementById(elem1).value;
            if (a == 90){
            a = 4
            }
            var b = document.getElementById(elem2).value;
            var c = Number(a) + Number(b);
            c = c / 8
            document.getElementById("testResult").innerHTML = c;
}
        
    </script>
</body>
</html>

For example if I add 2 and 2 and 12 instead of displaying 2 it displays 1.75 which is weird.

Advertisement

Answer

You forget to add the third values so you get wrong results.
If you inputs 2,2,12 result is 0.5, because of (2+2)/8 = 4/8 = 0.5.
For 2,12,2 or 12,2,2 result is 1,75 because of (2+12)/8 = 14/8 = 1,75

This should give you the desired result.

<html>
<head>
    <title>GPA Calculator</title>
</head>
<body>
    
    <input type="text" id="varA">
    <input type="text" id="varB">
    <input type="text" id="varC">
    <input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')">
    <h1 id="testResult"></h1>
    <script>
            function addNumbers(elem1, elem2, elem3) {
            var a = document.getElementById(elem1).value;
            if (a == 90){
            a = 4
            }
            var b = document.getElementById(elem2).value;
            var c = document.getElementById(elem3).value;
            let sum = Number(a) + Number(b) + Number(c);
            let result = sum / 8;
            document.getElementById("testResult").innerHTML = result;
}
        
    </script>
</body>
</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement