Hi there,

I have been trying to find a way to generate a random number within a range other than "1-X".

For example, the user will enter the low extreme and the high extreme - 20 and 80 perhaps. I have come up with a solution, but it doesn't seem very efficient. It bounces the number around until it satisfies the range.

I do have this working. What I'm wondering is if there is a better way to do it. Here's what I've got:

Code:
//l is for low extreme, h is for high extreme
int gen_rand(int l, int h) {
    srand(time(NULL));
    int my_rand = rand()%h +1;

    // (+/- 1) only - determines whether or not the number will
    // be reduced or increased in order to satisfy the given range
    int sign = 1;

    // if my_rand is lower than l (low range), add more - but if it goes above
    // h, subtract some.. repeat until my_rand is within the bounds of l and h.
    while (my_rand > h || my_rand < l) {
        if (my_rand > h) sign = -1; // we need to bring it down
        else if (my_rand < l) sign = 1; // bring it up
        my_rand += ((rand()%h)*sign) +1;
    }
    return my_rand;
}
I am a noob. I've tried multiple approaches to this and actually am lucky I was able to come up with even this. What I'm asking is whether or not there is a standard way of doing this (a common algorithm used "all the time") that I'm just missing.

I know that the code itself could probably stand some improvements, but I'm actually asking for help on the algorithm level, not the syntax level.

Thanks,
Kaelin