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

197
Visualizações
Math formula that is supposed to return whole numbers returns decimals (SOLVED)
for (i = 0; i < 100; i++) {
    result.innerHTML += 'when "i" is ' + i + ", the result is ";
    result.innerHTML += (i + seed) * (i + seed + 1) / 2 - seed + 1 + ";<br>";
}

when seed = 1; this equation should produce whole number outputs with the first being 1, but when the code is run the first result is 5.5 and continues to mess up from there. I have checked the equation many times and worked through the problem in Desmos but cannot figure out the answer.

I have debugged the inputs multiple times, but they are the correct whole number inputs. The first result, where i = 0 and seed = 1 should output 1, but instead outputs 5.5.

The result should be (0 + 1) * (0 + 1 + 1) / 2 - 1 + 1, which simplifies to 1 * 2 / 2, which equals 1, but somehow the computer doesn't calculate it this way. I used PEMDAS rules to attempt to get the correct result.

EDIT: The fix was parseInt();. When the calculation was being done, it concatenated two ones instead of adding them, and when it was divided by 2, it gave 5.5. It was because I got the seed value from an HTML input element.

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

0

I don't know where that math formula came from, but I just declared the initial result as zero and seed as 1. The first result number I get is 01.

let result = 0;
let seed = 1;

for (let i = 0; i < 100; i++) {
  result += ((i + seed) * (i + seed + 1)) / 2 - seed + 1 + '; ';
}
console.log(result);
about 4 years ago · Juan Pablo Isaza Relatório

0

Use parseInt, Math.ceil or Math.floor.

The division will always result in decimal value (for values that are not fully disvisible like 3/2, 4/3 etc).

parseIntwould solve your problem.

result.innerHTML += parseInt((i + seed) * (i + seed + 1) / 2 - seed + 1) + "; ";
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