0
I have declared a method for generating random numbers, but the results are almost always the same, because?
int geraAleatorio(int min, int max) {
return ((rand() % (max - min)) + min) + 1;
}
Is there any other algorithm?
0
I have declared a method for generating random numbers, but the results are almost always the same, because?
int geraAleatorio(int min, int max) {
return ((rand() % (max - min)) + min) + 1;
}
Is there any other algorithm?
1
We had to initialize the random seed. The random generator is not actually random so you need to randomize the seed, the most common is to use the computer clock.
You must only call the srand()
once in the application with the same argument. Otherwise it generates the same number.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int geraAleatorio(int min, int max) {
return ((rand() % (max - min)) + min) + 1;
}
int main(void) {
srand((unsigned)time(NULL));
printf("%d\n", geraAleatorio(10, 20));
printf("%d\n", geraAleatorio(10, 20));
printf("%d\n", geraAleatorio(30, 40));
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
That wasn’t the problem.
@hello Is what you put in the question.
0
Try to put this line before calling the function:
srand((unsigned) time(NULL));
Take a look at this old post will help you Random number range in C
Browser other questions tagged c random
You are not signed in. Login or sign up in order to post.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero