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);
Not working, it only generates the same numbers : 0,1,2,3 and 4.
– Monteiro
@Monteiro updated the answer. Run the online example several times, if possible. For me random numbers were generated within the requested range.
– mercador
@Vlw merchant brother, now worked out, I can not give yet +1, but I can give as correct answer.
– Monteiro