My variables are not being counted in the code

Asked

Viewed 102 times

-1

I’m creating a page for the user to enter an amount of numbers and stop only when he type the number 0, right after that, would open an alert telling the amount of numbers the user has typed, how many are negative, odd and even, but only part of the amount is working, could someone explain to me what I could do to solve the code?

<script>

    var quantidade = 0
    var negativos = 0
    var pares = 0
    var impares = 0

    while (numeros != 0) {
        var numeros = window.prompt("Digite os números para serem lidos")
        if (numeros != 0) {
            quantidade++;
        } else if (numeros < 0) {
            negativos++;
        } else if (numeros % 2 === 0) {
            pares++;
        } else if (numeros / 2 == 1) {
            impares++;
        }
    }

    alert(`Foram inseridos ${quantidade} números\n${negativos} são negativos\n${pares} são pares\n${impares} são ímpares.`)

</script>

3 answers

5


This is because of else if. The else is only assessed when a "contrary" condition occurs to the if.

Imagine you typed 1, the first if is:

if (numeros != 0) { - this condition is true, soon will enter here and will not enter in no other else if.

You can solve this by simply removing the else of the conditions:

while (numeros != 0) {
    var numeros = window.prompt("Digite os números para serem lidos")
    if (numeros != 0) {
        quantidade++;
    } 
    if (numeros < 0) {
        negativos++;
    } 
    if (numeros % 2 === 0) {
        pares++;
    } 
    if (numeros / 2 == 1) {
        impares++;
    }
}

But this will cause him to type zero if, and will add 1 pair, need to isolate it.
It can for example for all conditions only if the value differs from zero:

while (numeros != 0) {
    var numeros = window.prompt("Digite os números para serem lidos")
    if (!isNaN(numeros) && numeros != 0) {  // tudo é feito somente se "numeros" for diferente de zero
        quantidade++;
      
      if (numeros < 0) {
         negativos++;
      } 
      if (numeros % 2 === 0) {
          pares++;
      } else {  // senão for par, vai ser impar, não precisa avalisar o resto novamente
          impares++;
      }
    } 
}

Note that, in the if was added !isNaN(numeros) "if it’s not Nan". Nan means not a number, this to avoid trying to make calculations which values are not numbers, for example if you type a letter. Could even for a if isolated validating this:

if (isNaN(numeros)) {
    alert("Digite apenas números");
    continue;
}

Here was used continue to return the while, without continuing all the code below, since it is not a valid number :)

var quantidade = 0
var negativos = 0
var pares = 0
var impares = 0

while (numeros != 0) {
  var numeros = window.prompt("Digite os números para serem lidos")
  if (isNaN(numeros)) {
    alert("Digite apenas números");
    continue;
  }

  if (numeros != 0 ) {
    quantidade++;

    if (numeros < 0) {
      negativos++;
    } 
    if (numeros % 2 === 0) {
      pares++;
    } else {
      impares++;
    }
  } 
}


alert(`Foram inseridos ${quantidade} números\n${negativos} são negativos\n${pares} são pares\n${impares} são ímpares.`)

4

someone could explain to me what I could do to solve the code?

Rewrite the algorithm.

  • Within an infinite loop...
  • Convert the input numeros, which is returned by window.prompt() as String, in an object Number.
  • Test the conversion result to see if it is a number, use NumberisNaN(). If the conversion result is not a number, finish the iteration of the loop while and pass the next iteration with the command continue.
  • Test the conversion result to see if it is zero. If the conversion result is zero, the loop while with the command break.
  • Increments the amount of numbers computed.
  • Test the number to see if it is negative. If it is negative increment the variable negativos.
  • Test number parity. If number is even increment pares, otherwise increment impares;

var quantidade = 0
var negativos = 0
var pares = 0
var impares = 0

while (true) {
  var numeros = window.prompt("Digite os números para serem lidos");
  numeros = parseInt(numeros);
  if (Number.isNaN(numeros)) continue;
  if (numeros == 0) break;
  quantidade++;
  if (numeros < 0) negativos++;
  if (numeros % 2 == 0) pares++;
  else impares++;
}

alert(`Foram inseridos ${quantidade} números\n${negativos} são negativos\n${pares} são pares\n${impares} são ímpares.`)

1

 if (numeros != 0) {
            quantidade++;
        } else if (numeros < 0) {
            negativos++;
        } else if (numeros % 2 === 0) {
            pares++;
        } else if (numeros / 2 == 1) {
            impares++;
        }

as the first condition if was answered, the code was not even read after the else. What’s in the noose of else is only read if the condition for the if previous is not satisfied.

Browser other questions tagged

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