I want to generate random numbers from -n to n excluding 0. Can someone provide me the code in C? How to exclude 0?
One idea might be to generate a random number x
in the range [1,2n], inclusive. Then return -(x - n)
for x
larger than n
, else just return x
.
This should work:
int my_random(int n)
{
const int x = 1 + rand() / (RAND_MAX / (2 * n) + 1);
return x > n ? -(x - n) : x;
}
See the comp.lang.c FAQ for more information about how to use rand()
safely; it explains the above usage.
The simplest thing I can suggest to do is to generate a Random number between 0 and 2n and then to do the math trick:
result= n - randomNumber
Although 0 might be very unlikely you can check for that using an If and redo the random number generation.
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