Random Number

Dear sir

i posted in the last three days a question and a get the reply for it, but i have another question, which is

how can i get a random number between two ranges ( i can get an integer random number between one range as shown in the code below) for example i can get integer number between (range_min, range_max), but my problem is how to get a random number can be in one of the two ranges (range_min1, range_max1) and (range_min2, range_max2) ( e.g. between (0 and 200) or(400 and 1000))


int RangedRandDemo( int range_min, int range_max)
errno_t err;
unsigned int number;

err = rand_s( &number );
if (err != 0)
{
printf_s("The rand_s function failed!\n");
}
return (unsigned int) (((double)number /
(double) UINT_MAX * range_max) + range_min);
}


i used a the code shown below but this one sometimes it get the random number in one or two trials and other time it get it in more ( which is time consuming)

do
{
RandomNum = RangedRandDemo(1,1000);
}while((myNextState >=200)&&(myNextState <400));

i gave the example of (0 and 200) or(400 and 1000) but in my problem the gap between the two ranges are bigger.

is there a way to get a random number between two ranges.

with best wishes and very thank you for your help in the first problem
rand_s()
Ew! What are you doing?

1
2
3
int max=?,
    min=?;
int n=rand()%(max-min)+min; //produces a random number in the interval [min;max) 

The above will not work if max-min>RAND_MAX.
hi helios

the above code is working fine if i want to get random integer between one range , but, in your code the possibility the random number repeated is more likely , but the above code the possibility of repeated random are slim.

i am asking is there a way to get a random number between two ranges instead of one range as a explained above

max-min can not be greater than RAND_MAX ( because RAND_MAX is the maximum number in long double)
Last edited on
How about you generate an initial random number with only 2 possible numbers, 0 and 1 for example. Then say if that first random number was 0 use a certain range, or if it was 1, use a different range.
Last edited on
Topic archived. No new replies allowed.