如何在随机数生成中包含负数

时间:2016-04-12 16:28:57

标签: c visual-studio-2013

这是从(-1,36)生成随机数的正确方法吗?:

  #include <stdio.h>
  #include <stdlib.h>
  #define RAND_MAX 36

  int main()
  {           
      int num = (-1) + (36 + 1) * (rand()/(RAND_MAX+1));
      printf("%d\n", num);
      return 0;
  }

3 个答案:

答案 0 :(得分:4)

您知道如何获得0到N范围内的随机数(其中N是您想要的最大数量)?然后,您知道如何生成-NN范围内的数字。

只需生成02*N范围内的数字,然后减去N

更新:要生成-136范围内的数字,您应该从0生成37并减去1

但两种情况的原则相同。

答案 1 :(得分:0)

不,这不是正确的方法。

首先,您不应该#define RAND_MAX 36因为RAND_MAX已经是一个定义,告诉您系统将生成最大值rand()

一个非常简单的解决方案是:

要获得[0:37]范围内的数字,你可以

rand() % 38;  // % is the reminder when dividing by 38 - aka modulo

然后只是`减去1

但是 - 请参阅此链接以获得更好的分发

Why do people say there is modulo bias when using a random number generator?

答案 2 :(得分:0)

这取决于您是否尝试从integers生成floats-136

integers

1)首先,生成从0N的范围。从-136(包括),您有38个整数。

rand()%38; //this generates a range of integers from 0 to 37.

2)改变范围:

rand%38 - 1; //this shifts the range of numbers to -1 to 36.

对于floats(或带小数点的数字):

1)生成从01的“连续”范围。

( 1.0*rand() )/RAND_MAX; //do not forget to convert rand() to a float so that you will not get 0 from integer division.

2)缩放范围:

37 * ( (1.0*rand() )/RAND_MAX; //this scales the range to (0, 37)

3)改变范围:

37 * ( (1.0*rand() )/RAND_MAX - 1; //this shifts to range (-1, 36)