Javascript function that receives three numbers as parameters and returns the largest

Asked

Viewed 1,089 times

4

I need to create a function that takes three numbers as parameters and returns the largest of them. If two or three are equal, it shows the same value.

I was able to make the comparison, but it remains to show that if it has a repeated value it shows this value.

Fiddle

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() {
    var a = Array.prototype.sort.call(arguments);
    alert( "O maior número é: " + a[a.length - 1] + " e o menor é: " + a[0]);
}

maiorDosTres(n1, n2, n3);Q
  • "If two or three are equal, it shows the same value" - This premise does not affect at all the original objective. If you show the largest, it will be valid for all different elements, as for any quantity of larger elements equal.

  • Or the goal is to know if the largest element is repeated or single ?

2 answers

6

Math.max() - returns the largest of one or more numbers

var n1 = parseFloat(prompt("Digite um número:"));
var n2 = parseFloat(prompt("Digite um número:"));
var n3 = parseFloat(prompt("Digite um número:"));

var numbers = [n1, n2, n3];

var sorted_arr = numbers.sort();  
var results = [];
for (var i = 0; i < numbers.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}
var repetido = (results[0]);

if (results!=""){
  console.log(repetido);
}else{
  console.log(Math.max(n1, n2, n3));
}

  • What if they have equal numbers, like 1,1, 2? will return 2

  • @Sam, 2 is bigger than the first 1 and also bigger than the second 1 :)

  • But it should return 1 because it has equal. See the question: "If two or three are equal, shows the same value."

  • @sam, but where did you see that if it is 1,1, 2, does not return 1? :)

-1

As there are only 3 numbers and in case there are any repeated that return him, in this case only two numbers are equal to meet this criterion.

Explanations in the code:

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() {
    var a = [].sort.call(arguments);
    var maior = a[2]; // seleciona o último número
    var menor = a[0] // seleciona o primeiro número
    var msg = maior == a[1] || menor == a[1] ? // se o primeiro ou o último for igual ao segundo
      "Número repetido: "+ (maior == a[1] ? maior : menor) // mostra essa mensagem selecionando o que foi igual
      :
      "O maior número é: " + maior + " e o menor é: " + menor; // ou então mostra essa mensagem quando não houve repetidos

    alert(msg);
}

maiorDosTres(n1, n2, n3);

Browser other questions tagged

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