Reputation: 5
I was trying to build an MCT calculator in javascript, however during the creation of the median, I kept getting errors. This is my code: (Keep in mind I am relatively new to javascript)
var min = prompt("Enter minimum value");
var max = prompt("Enter maximum value");
if (min > max) {
alert("Error:\n\n\nMinimum value '" + min + "' is greater than Maximum value '" + max + "'");
} else {
var a = (max - min);
alert("variable a is " + max + " - " + min + " = " + a);
var b = a / 2;
alert("variable b is " + a + " / 2 = " + b);
var c = min + b;
alert("variable c is " + min + " + " + b + " = " + c);
alert("Range is " + a + "\n\nMedian is " + c + "\n\nMin is " + min + "\n\n Max is " + max);
}
If you type in 5 for minimum value and 10 for maximum value, it will tell you 5 is larger than 10, but it isn't.. And if you type 10 for minimum value and 15 for maximum value, it will have the median be 102.5 rather than 12.5 I do not get this at all, please help :)
Upvotes: 1
Views: 99
Reputation: 149050
The prompt
function returns a string, and strings are compared according to the Unicode code points of each character in the string (also called lexicographical or alphabetical order). The code point of "5"
is greater than the code point of "1"
, so the string "5"
actually is greater than the string "10"
(i.e. comes after it in lexicographical ordering) .
Try parsing the inputs like this:
var min = parseFloat(prompt("Enter minimum value"));
var max = parseFloat(prompt("Enter maximum value"));
Upvotes: 1
Reputation: 253446
Try using numbers, not strings:
var min = parseInt(prompt("Enter minimum value"), 10);
var max = parseInt(prompt("Enter maximum value") , 10);
Or, if you want to allow for floats:
var min = parseFloat(prompt("Enter minimum value"));
var max = parseFloat(prompt("Enter maximum value"));
This because strings are compared lexicographically, using their numerical character codes, rather than the value of the number itself.
Upvotes: 4