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.
JavaScript
x
28
28
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title>GPA Calculator</title>
5
</head>
6
<body>
7
8
<input type="text" id="varA">
9
<input type="text" id="varB">
10
<input type="text" id="varC">
11
<input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')"></input>
12
<h1 id="testResult"></h1>
13
<script>
14
function addNumbers(elem1, elem2, elem3) {
15
var a = document.getElementById(elem1).value;
16
if (a == 90){
17
a = 4
18
}
19
var b = document.getElementById(elem2).value;
20
var c = Number(a) + Number(b);
21
c = c / 8
22
document.getElementById("testResult").innerHTML = c;
23
}
24
25
</script>
26
</body>
27
</html>
28
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.
JavaScript
1
27
27
1
<html>
2
<head>
3
<title>GPA Calculator</title>
4
</head>
5
<body>
6
7
<input type="text" id="varA">
8
<input type="text" id="varB">
9
<input type="text" id="varC">
10
<input type="button" value="Add" onclick="addNumbers('varA', 'varB', 'varC')">
11
<h1 id="testResult"></h1>
12
<script>
13
function addNumbers(elem1, elem2, elem3) {
14
var a = document.getElementById(elem1).value;
15
if (a == 90){
16
a = 4
17
}
18
var b = document.getElementById(elem2).value;
19
var c = document.getElementById(elem3).value;
20
let sum = Number(a) + Number(b) + Number(c);
21
let result = sum / 8;
22
document.getElementById("testResult").innerHTML = result;
23
}
24
25
</script>
26
</body>
27
</html>