在C中生成从-n到n的随机数

avd*_*avd 5 c random

我想生成从-n到n的随机数,不包括0.有人能为我提供C代码吗?如何排除0?

unw*_*ind 9

一个想法可能是生成x[1,2n]范围内的随机数.然后返回-(x - n)x大于n,否则直接返回x.

这应该工作:

int my_random(int n)
{
  const int x = 1 + rand() / (RAND_MAX / (2 * n) + 1);

  return x > n ? -(x - n) : x;
}
Run Code Online (Sandbox Code Playgroud)

有关如何安全使用的更多信息,请参阅comp.lang.c常见问题解答rand() ; 它解释了上述用法.