Range of values to compare

Asked

Viewed 59 times

0

When I ask for a random value on Math.Random() I want him to say whether it was normal, disaster or failure, but I can’t get him to talk normal because I need him to say when he’s over 2 and under 19 he failed. Needs to be roll1 > 2 and < 19.

if (roll1 == 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19){
    console.log(`FALHOU`);
  }
  if (roll1 == 20){
    console.log(`NORMAL`);
  }
  if (roll1 == 1){
    console.log(`DESASTRE`);
  }
}

  • You should use comparison operators x < y and x > y, or if you want it to be from 2 until 19 use the x >= y and x <= y in IF, the first IF could be if (roll1 >= 2 && roll1 <= 19){, using && to check that both conditions are correct.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

Test which is easier first, which is unique value, so do this with 1 and 20, then what’s within that range is what’s left, you don’t need to test explicitly, it’s the exception, so it already falls into else if it is not any of the numbers you have tested differently.

And take care that all conditions are bound, the else if serves for this, the execution will fall only on one of the if or else, is a selection of the most suitable, the first one he enters nor tries others, the else alone ensures that you will enter there if you do not enter any if previous. He is like a else if (true).

You need to make sure you can’t give it another value, I imagine not, since the code indicated that.

var roll1 = 3;
if (roll1 == 1) {
    console.log(`DESASTRE`);
} else if (roll1 == 20) {
    console.log(`NORMAL`);
} else {
    console.log(`FALHOU`);
}

I put in the Github for future reference.

If you can have other values then you have to change:

var roll1 = 3;
if (roll1 == 1) {
    console.log(`DESASTRE`);
} else if (roll1 == 20) {
    console.log(`NORMAL`);
} else if (roll1 > 1 && roll1 < 20) {
    console.log(`FALHOU`);
} else {
    console.log(`Deu número inválido`);
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.