-1

I would like to check 3 numbers:

  • If the three numbers are same I have to display 30,
  • If two numbers are same I display 40,
  • Otherwise, I display 20.

When, I enter 3 numbers for example:

8
8
8

The output displays

30
40

Normally, the output is 30. Why is the value 40 added also?

enter image description here

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


if (nb1 == nb2 && nb2 == nb3) {
    console.log(30);
}

if (nb1 == nb2 || nb2 == nb3 || nb3 == nb1) {
    console.log(40);
}

else {
    console.log(20);
}

Thanks

solange
  • 103
  • 1
  • 1
  • 6
  • 7
    Use `else if` for the second condition. – kelsny Sep 01 '22 at 14:36
  • 3
    Did you mean for your second `if` to be an `else if`? Because logically *every* time the first `if` is `true` then so will the second. – David Sep 01 '22 at 14:36
  • 2
    There both displayed because both the `if` resolve to `true`, use `else if` like Kelly suggest to prevent the second `if` from checking if the first `if` is `true` already – 0stone0 Sep 01 '22 at 14:37
  • 2
    As an aside... This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? This should always be your first step when diagnosing an unexpected result of your code. – David Sep 01 '22 at 14:39

1 Answers1

2

Use the second if in an else if block. Both of the first two ifs are true when 3 numbers are equal.

imoxto
  • 144
  • 5