Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
Why does same javascript code give different result?

I am a beginner at javascript. I find following piece of code a bit difficult for me. I think both are same, and should have give the same result. But they are throwing different result.

var a = 5,
  b = 6,
  c = 7;

if (a + b > c || b + c > a || a + c > b) {
  let s = (a + b + c) / 2;
  let area = Math.sqrt(s * ((s - a) * (s - b) * (s - c)));
  console.log(`The area of the triangle is: ${area}`);
} else {
  console.log('Triangle does not exist');
}

It gives me a result. But when i try to take input from user and input the same value (5,6,7), find different result.

var a = prompt(),
  b = prompt(),
  c = prompt();

if (a + b > c || b + c > a || a + c > b) {
  let s = (a + b + c) / 2;
  let area = Math.sqrt(s * ((s - a) * (s - b) * (s - c)));
  console.log(`The area of the triangle is: ${area}`);
} else {
  console.log('Triangle does not exist');
}

Maybe I am wrong. But I just want know the reason.

Thanks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

My assumption is that this is related to prompt() returning a string and not an integer. Therefore the additions of the variables a, b and c would concatenate the strings and only after that - caused by the comparison > and after division / - convert it to a number. So in order to fix this, I think using parseInt() to parse the numbers returned from prompt() would fix the issue

about 4 years ago · Juan Pablo Isaza Relatório

0

The promt causes the variables to be defined as a string and as @Barmar pointed out in his comment, this changes the behavior of the '+' operation in your if-statement.

With numbers 1 +1 is returned as 2, with strings 11. What you can do is change the following: let s = (a + b + c) / 2;will give you 567/2 as you have strings. let s = (parseInt(a) + parseInt(b) + parseInt(c) ) / 2; will give you the desired result as the method parseInt() returns a intger value.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda