Generate random numbers in C?

Asked

Viewed 10,220 times

3

I need to generate 5 random numbers in a range between -10 and +10. How could I do this ? I’ve seen that one can use shuffle, malloc or even realloc, but being new in C, I don’t quite understand how I can make it work. If anyone can help me, I would be grateful.

The only part of my code is that I have created the array with size 5, so I can then try to generate the random numbers.

Code :

include <stdio.h>
include <stdlib.h>
include <locale.h>

int main() {
    setlocale(LC_ALL,"portuguese");
    int num[5] // este será a variável que irei usar para gerar números aleatórios. 
    return 0;
}

I also want to check whether the numbers that were randomly generated are positive or negative. But when doing the check, even if it gives 5 positive numbers, it puts negative as 1.

Code :

int positivo;
int negativo;

if(num[i] > 0) {
    positivo += 1;
}
else if(num[i] < 0 ) {
    negativo += 1;
}

printf("\nPositivo(s) : %d ",positivo);
printf("Negativo(s) : %d ",negativo);

1 answer

5


See the function documentation srand() (in English).

An example would be like this:

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

srand(time(NULL));   // Só deve ser chamada uma única vez
int r = rand();      // Retorna um número inteiro pseudo-aleatório entre 0 and RAND_MAX

The value of the macro RAND_MAX is at least 32767.

To limit your result between -10 and 10, use the module operator % and a subtracting value:

int i;
for (i = 0; i < 5; i++) {
    num[i] = (rand() % 21) + (-10); // Veja [1]
}

[1] rand() % N returns an integer in the closed range [0, N-1]. With N=21, the break will be [0, 20]. As you want within the closed interval [-10, 10], just subtract 10 of the result.

Edit Complete online example here, keeping the amount of positive and negative numbers.

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

int main() {
    int i;
    int num[5];
    int positivo = 0; // DEVE inicializar
    int negativo = 0; // DEVE inicializar

    srand(time(NULL));

    for (i = 0; i < 5; i++) {
        num[i] = (rand() % 21) + (-10);
        if (num[i] > 0) {
            positivo += 1;
        }
        else if (num[i] < 0 ) {
            negativo += 1;
        }
    }

    for (i = 0; i < 5; i++) {
        printf("[%d]: %d\n", i, num[i]);
    }

    printf("Positivo(s) : %d\n", positivo);
    printf("Negativo(s) : %d\n", negativo);

    return 0;
}

You cannot create a non-static variable (local variable) and increment it without initializing it. Local variables are undetermined. In practice, initially they tend to have only some meaningless value.

  • Not working, it only generates the same numbers : 0,1,2,3 and 4.

  • @Monteiro updated the answer. Run the online example several times, if possible. For me random numbers were generated within the requested range.

  • 1

    @Vlw merchant brother, now worked out, I can not give yet +1, but I can give as correct answer.

Browser other questions tagged

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