Show highest and lowest number

4

Why are you wrong?

var n1 = parseFloat(prompt("Digite um número:"));
var n2 = parseFloat(prompt("Digite um número:"));
var n3 = parseFloat(prompt("Digite um número:"));
function maiorDosTres(n1, n2, n3) {
  if ( n1 > n2 > n3) {
    alert( "O maior número é: " + n1 + " e o menor é: " + n3);
  } else if ( n1 > n3 > n2) {
    alert( "O maior número é: " + n1 + " e o menor é: " + n2);
  } else if ( n2 > n1 > n3) {
    alert( "O maior número é: " + n2 + " e o menor é: " + n3);
  } else if ( n2 > n3 > n1) {
    alert( "O maior número é: " + n2 + " e o menor é: " + n1);
  } else if ( n3 > n1 > n2) {
    alert( "O maior número é: " + n3 + " e o menor é: " + n2);
  } else if ( n3 > n2 > n1) {
    alert( "O maior número é: " + n3 + " e o menor é: " + n1);
  }
}
maiorDosTres(n1, n2, n3);
    
asked by anonymous 29.08.2015 / 19:09

4 answers

11

It's wrong because you can not buy more than two operands at the same time. This does not exist:

if ( n1 > n2 > n3) {

The correct one would be:

if ( n1 > n2 && n2 > n3) {

This way you have three expressions with two operands each: n1 > n2 , n2 > n3 and the relational operation && that has the results of the previous expressions as operands.

The same goes for the others. I think you've got the hang of it.

There are better ways to do this. Using Math.max() and Math.min() would be one of them. I will not put it because it seems to me that you are doing this for study purposes and you do not want the best solution.

    
29.08.2015 / 19:32
9

You can use the functions Math.max() and Math.min() . The two functions are given all values for comparison as parameters. Although the question is the reason for being wrong, this form will make your code leaner.

var n1 = 10;
var n2 = 5;
var n3 = 7;

var max = Math.max(n1, n2, n3);
var min = Math.min(n1, n2, n3);

var pre = document.body.appendChild(document.createElement('pre'));
pre.textContent = 'dos valores ' + n1 + ', ' + n2 + ' e ' + n3;
pre.textContent += ' o máximo é ' + max + ' e o mínimo é ' + min;

If the data is in an array use apply() :

var numeros = [4,6,2,7,9,5];
Math.max.apply(Math, numeros);
    
31.08.2015 / 13:38
1

Write the values in an array and use the "for" for this case, the function becomes more flexible and serves for any number of arguments:

var n = [1, 2, 3];


numero=n(i)

for (i = 0; i < n.length; i++) { 
    if (n(i) >= numero) { maior = n(i); }
    if (n(i) <= numero) { menor = n(i); }
}
alert( "O maior número é: " + maior + " e o menor é: " + menor);
    
31.08.2015 / 12:12
1

Why not sort the numbers?

function maiorDosTres() {
    var a = Array.prototype.sort.call(arguments);
    alert( "O maior número é: " + a[a.length - 1] + " e o menor é: " + a[0]);
}

Fiddle

    
31.08.2015 / 13:37