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

368
Visualizações
What will Math.floor(Math.random() * 10 + 1); do

I came across the following command:

Math.floor(Math.random() * 10 + 1); 

I understand that Math.floor() will convert to the lowest integer, but what does Math.random() * 10 + 1 do?

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

0

Math.random returns a floating point number x such that:

enter image description here

Multiplying 10 to x yields a floating point number in the range:

enter image description here

And then adding 1 to 10x yields a floating point number in the range:

enter image description here

And finally flooring 10x + 1 yields an integer in the range:

enter image description here

Therefore, Math.floor(Math.random() * 10 + 1) yields an integer that lies in the range [1, 10].

about 4 years ago · Juan Pablo Isaza Relatório

0

Math.random generates a random number between 0 and 1. So for example it can be .124 or .42242. When you multiply this random number against something, you are basically making it so that the new result is no less than 0, but no more than the number you are multiplying it against.

So in your example, you are multiplying it against 10, which means you will get a random number between 0 and 10 with decimals; technically this range is 'more than 0, but less than 10'. The +1 just increases the total range so that it is between 1 and 11, or 'more than 1, but less than 11.

When you apply Math.floor() to this, you are rounding all of these results down. So in the case without the '+1', your finite range is actually 0-9, and with the +1 it is 1-10

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