Generate random numbers in C?
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 because I'm new to C, I don't quite understand how I can make it work. If anyone can help me, I'll be grateful.
The only part of my code, is only 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 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 answers
See function documentation srand()
(in English).
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 macro RAND_MAX
is at least 32767.
To limit your result between -10
and 10
, use the module operator %
and a value subtracting:
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 range will be [0, 20]
. As you want within the closed range [-10, 10]
, just subtract 10
from the result.
Edit complete example online 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 cannot 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.