When I enter 3 numbers for example:
1000
510
440
The output displays
510
instead of 1000
let readline = require("readline-sync");
let nb1 = readline.question("Enter nb1 please : ");
let nb2 = readline.question("Enter nb2 please : ");
let nb3 = readline.question("Enter nb3 please : ");
let biggest = nb1;
if (nb2 > biggest) {
biggest = nb2;
}
if (nb3 > biggest) {
biggest = nb3;
}
console.log(biggest);
I don't understand the problem ?
Can you help me solve the problem?
CodePudding user response:
This is because your answers are not numbers but strings. Sorting on strings will read from right to left (1 is lesser than 5 so 510 will stay on top)
What you need would be to cast every answers as number, or use String.localeCompare with the numeric
option passed so it knows how to compare those strings.
let readline = require("readline-sync");
let nb1 = parseInt(readline.question("Enter nb1 please : "));
let nb2 = parseInt(readline.question("Enter nb2 please : "));
let nb3 = parseInt(readline.question("Enter nb3 please : "));
let biggest = nb1;
if (nb2 > biggest) {
biggest = nb2;
}
if (nb3 > biggest) {
biggest = nb3;
}
console.log(biggest);
Here is the example for the numeric comparison: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#numeric_sorting
Note that localeCompare will return -1, 0 or 1, and is mostly used as a sort function comparator
CodePudding user response:
This is happening because when you are reading input from terminal the value stored in variable is in string data type and also in if conditions the comparison is between strings not integer values you have to first convert your input to integer values here is the solution I used Number function to convert string to interger.
let readline = require("readline-sync");
let nb1 = Number(readline.question("Enter nb1 please : "));
let nb2 = Number(readline.question("Enter nb2 please : "));
let nb3 = Number(readline.question("Enter nb3 please : "));
let biggest = nb1;
if (nb2 > biggest) {
console.log("nb2");
biggest = nb2;
}
if (nb3 > biggest) {
biggest = nb3;
}
console.log(biggest);