Generating random numbers from -n to n in C

I want to generate random numbers from -n to n, excluding 0. Can someone provide me code in C? How to exclude 0?

+5
source share
3 answers

One idea might be to create a random number xin the range [1,2n] inclusive. Then return -(x - n)for xmore than n, otherwise 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 on how to use it safely rand(); this explains the above use.

+9
source

, , 0 2n, :

result= n - randomNumber 

0 , , If .

+3
int random(int N) 
{ 
  int x;
  do{
    x=rand()%(N*2+1)-N;
  }while(x==0);
  return x;
}

He selects a number from -N to N, but continues to do so if it is 0.

An alternative, as suggested in the comments, generates a number between -N and N-1 and increments it if it is positive or 0:

int random(int N) 
{ 
  int x;      
  x=rand()%(N*2)-N;
  if(x>=0) x++;
  return x;
}
+1
source

All Articles