这是从(-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;
}
答案 0 :(得分:4)
您知道如何获得0到N
范围内的随机数(其中N
是您想要的最大数量)?然后,您知道如何生成-N
到N
范围内的数字。
只需生成0
到2*N
范围内的数字,然后减去N
。
更新:要生成-1
到36
范围内的数字,您应该从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
或-1
到36
。
〜
integers
:
1)首先,生成从0
到N
的范围。从-1
到36
(包括),您有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)生成从0
到1
的“连续”范围。
( 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)