Find max and min in Javascript without using array

1

I need to find the maximum and minimum of a sequence of numbers that the user enters, at random, until he wants to. I mean, it could be 2 numbers like 356, if you want to.

I can only use while and if, and not for.

So far I have this:

  var seguir;
	var numero;
	var maximo;
	var minimo;

	do {
		numero = parseInt(prompt("Ingrese numero"));
		while (isNaN(numero)) {
			numero = parseInt(prompt("Error. Ingrese numero"));
		}
		if (numero < minimo) {
			minimo = numero;
		}
		if (numero > maximo){

			maximo = numero;
		}

		seguir = confirm("Desea continuar?");
	}

	while (seguir);
  
  console.log("max: " + maximo + " Minimo: " + minimo)

But it only shows undefined .

Thank you very much.

    
asked by bornlivedie 06.03.2017 в 17:54
source

2 answers

1

I have changed your Do While for a While and I have initialized seguir to true and the variables of maximum and minimum number to the minimum and maximum possible value respectively

var seguir = true;
	var numero;
	var maximo = Number.MIN_VALUE;
	var minimo = Number.MAX_VALUE;


	while (seguir){
  
		numero = parseInt(prompt("Ingrese numero"));
		while (isNaN(numero)) {
			numero = parseInt(prompt("Error. Ingrese numero"));
		}
		if (numero < minimo) {
			minimo = numero;
		}
		if (numero > maximo){

			maximo = numero;
		}

		seguir = confirm("Desea continuar?");
	}

  console.log("max: " + maximo + " Minimo: " + minimo)
    
answered by 06.03.2017 / 18:00
source
0

You should initialize the minimum with a very large number because if you start it with zero unless you put a negative number the minimum will always be zero

    
answered by 06.03.2017 в 18:03