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

179
Visualizações
Random number range, exclude 0

I have the following function that generates a random number between -10 and 2:

#include <stdlib.h>
#include <time.h>

static int
getRandomReturnCode(void)
{
    int N = 2,
        M = -10;

    srand(time(NULL));

    r = M + rand() / (RAND_MAX / (N - M + 1) + 1);

    if (r == 0){
        getRandomReturnCode();
    }

    return r;
}

Currently, if a return code of 0 (success) is returned, it will recursively call the function over until a non-zero return code is met and returned. What can I do to improve my code such that 0 is excluded from the range of randomly chosen numbers?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Whatever you do, don't redraw if a returned value is 0: that will introduce statistical bias into the result.

The best thing to do here is to draw between -10 and 1 inclusive and add 1 to any non-negative output.

Finally, call srand once else you'll ruin the generator's statistical properties.

(Briefly - since this comment is more for the mathematics site - and restricting the argument to a linear congruential generator, what tends to happen if you omit generated values is that you increase the variance of the resulting distribution so it's no longer uniform. A previously drawn small number will be linearly related to the subsequent drawing as the generator's modulus will have no effect. This autocorrelation - necessary for the resulting distribution to be uniform - of adjacent drawings will be curtailed if drawings are discarded and that increases the sample variance.)

over 4 years ago · Santiago Trujillo 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