Generate random numbers in C?

2

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

The only part of my code, it's only 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 if the numbers that were randomly generated are positive or negative. But when doing the verification, even if it gives 5 positive numbers, it places 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);

    
asked by anonymous 04.06.2017 / 23:06

1 answer

4

See the srand() documentation.

An example would look 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 RAND_MAX macro 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 interval will be [0, 20] . As you want within the closed range [-10, 10] , just subtract 10 from the result.

Edit Complete online example here , saving 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 can not create a non-static variable (local variable) and increment it without initializing it. Local variables are indeterminate. In practice, initially they tend to have only some meaningless value.

    
04.06.2017 / 23:32