I'm trying to create 2 random numbers (between 0-4 and 0-10) in each time the cycle occurs, but it always give the same number. If I run the program multiple times, it gives different numbers, but the while cycle always generates the same 2 numbers. thanks.
int random(int range){
int num;
srand(time(NULL));
num = rand() % range;
return num;
}
int main(){
int cnt = 0;
int i;
int j;
while (cnt <= 20) {
i = random(5);
j = random(10);
printf("%d\n",i);
printf("%d\n",j);
printf("\n");
cnt += 1;
}
return 0;
}
You only need to seed the random number generator once.
So run this line outside of your random function:
srand(time(NULL));
.. in your main function instead:
int random(int range){
int num;
num = rand() % range;
return num;
}
int main(){
int cnt = 0;
int i;
int j;
// Seed random number generator
srand(time(NULL));
while (cnt <= 20){
i = random(5);
j = random(10);
printf("%d\n",i);
printf("%d\n",j);
printf("\n");
cnt += 1;
}
return 0;
}
You require to seed the random function just once. Include the time.h library and use
#include<time.h>
.....
srand(time(NULL));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With