How to use the while command to show the lowest value typed by the user?

Asked

Viewed 65 times

1

People I’m having trouble solving the following problem:

Create an algorithm that takes multiple numbers and closes the reading when the user type the zero, at the end it should show the smallest of the numbers typed.

var numero, menor = 1 
numero = prompt("Digite um numero: ")

while(numero != 0){ 
   if(menor < numero){
      menor = numero
   }

   document.write("Menor valor digitado é:  ", menor)     
}
  • 2

    Where is the code?

  • DSCLP I’m new here, I edited my question so you can see the code

1 answer

2

You can do it this way:

var numero, menor;
while(numero != 0){
   numero = +prompt("Digite um numero: ");
   if(numero == 0){
      document.write("Menor valor digitado é:  ", menor ? menor : "nenhum número foi digitado");
      break;
   }

   if(!menor || numero < menor){
      menor = numero;
   }
}

Explaining:

The prompt returns a string. Adding the sign of + before will convert the number typed in type Number:

+prompt("Digite um numero: ")

You need to do this conversion because otherwise you will compare strings, and "10" is less than "5", for example.

And the prompt should be inside the while otherwise it will generate an infinite loop, because if a different number of 0, the while will run forever, and the prompt will not be called again.

Another thing is to declare the variable menor worthless, because if it is 1, no number entered at the prompt will be lower (I am not considering the possibility of entering negative number in your original code).

The second if checks whether the value of menor is undefined or less than the number typed. Any of these conditions will reassign the entered value to the variable.

If the user type 0, will display the message and stop the while with break, since it doesn’t matter anymore.

  • Thank you so much for your help!!!!!!!!!!

Browser other questions tagged

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