-1

When I enter 3 numbers for example:

1000
510
440

The output displays

510 instead of 1000

enter image description here

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?

solange
  • 103
  • 1
  • 1
  • 6
  • 2
    I suspect that `readline.question()` is returning a string; you'll probably want to convert to a number. And I think your method works, but I'd probably use `Math.max(nb1,nb2,nb3);` – mykaf Aug 31 '22 at 14:42
  • Does this answer your question? [javascript if number greater than number](https://stackoverflow.com/questions/13079626/javascript-if-number-greater-than-number) – Ivar Aug 31 '22 at 14:46
  • 1
    You might want to read more about `questionInt` method [here](https://www.npmjs.com/package/readline-sync#questionint) – amlxv Aug 31 '22 at 14:51

2 Answers2

1

This is because your answers are not numbers but strings. Sorting on strings will read from left to right (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

nook
  • 1,729
  • 1
  • 12
  • 34
1

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);