Reputation: 14441
I want to generate random numbers from -n to n excluding 0. Can someone provide me the code in C? How to exclude 0?
Upvotes: 5
Views: 562
Reputation: 5491
int random(int N)
{
int x;
do{
x=rand()%(N*2+1)-N;
}while(x==0);
return x;
}
It chooses a number from -N to N, but keeps on doing it if it is 0.
An alternative, as suggested in the comments, generates a number between -N and N-1 and increments it if its positive or 0:
int random(int N)
{
int x;
x=rand()%(N*2)-N;
if(x>=0) x++;
return x;
}
Upvotes: 1
Reputation: 399803
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.
Upvotes: 9
Reputation: 9509
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.
Upvotes: 3