int main() { for(register char c = 0; c < 5; c++) { printf("%c\t", myrand(33, 126)); }
putchar('\n'); return 0; }
Name:
Anonymous2019-09-11 7:00
what are you even trying to achieve? I guess it is to have a RNG which returns numbers between between min and max. the way to do it correctly would be new_value = min + rand() % (max-min), as the current implementation doesn't do this correctly. the loop is entirely unnecessary - there is no need to ensure that new value is different than previous, as random numbers can repeat. I guess your're are problem was that you were getting the same number repeated all the time, but this is because your're are using srand() wrong. it re-seeds the global RNG, so calling it should not be the responsibility of myrand() but of the calling program. also, unrelated to speed: returning 1 is weird here because 1 is a valid return value of an RNG, I'd rather use errno to indicate wrong arguments. a rough solution would look like this (warning: I did not compile it):
int myrand(int min, int max) { static short seeded = 0; //assuming your're are using a standard from before bool type if(!seeded){ srand(time(NULL)); seeded = 1; } if(min > max){ errno = EINVAL; return 0; } return min + (rand()%(max-min)); }
int main() { for(register char c = 0; c < 5; c++) { printf("%c\t", myrand(33, 126)); }