I've been trying to write a small C function for generating random values. The problem is that it returns same value each time the function is called in for loop. I understand the problem is that srand is seeded with NULL. What I want to know is how to correct it, so that on each iteration of for loop the function returns a different value. Here's the code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int,int);
void main(){
int min=100, max=200,i=0;
for(i;i<11;i++){ printf("%d \n",randInt(min,max)); }
}
int randInt(int a,int b){
srand(time(NULL));
int randValue;
randValue=1+(int)rand()%(b-a+1);
return randValue;
}
Please let me know if you have a solution or can post some reference to a solution. Thank you in advance !
Edit : Encountered Problem #2, after having replaced srand(time(NULL)) into main, every iteration now generates numbers bellow my range, i.e. originally i wanted numbers between 100 and 200, but it also included numbers between 0 and 100. This was solved with randValue=a+(int)rand()%(b-a+1); as suggested in the comments
srandinside the random function.srand(time(NULL));just after mainsrand(time(NULL));inmain()trick does not work to "make random value function return different value each time" if the code is executed twice in the same second. An alternative is to pull theseedinsrand(seed)value from a file and increment it each program run. Many approaches exist to solve this problem.