rand()在C中做什么?我不使用C ++,只是C. Visual Studio 2012告诉我它的返回类型是int __cdecl 它是stdlib.h的一部分 它不需要任何参数。 如何设置生成(伪)随机数的范围? 非常感谢您的回答
答案 0 :(得分:0)
取决于编译器。这篇wiki文章包含它们的列表:linear congruential generator
如果你需要扩展rand()的范围,多次调用它并合并输出:
unsigned int r;
/* ... */
r = ((rand()>>4) & 0xff)<< 0;
r += ((rand()>>4) & 0xff)<< 8;
r += ((rand()>>4) & 0xff)<<16;
r += ((rand()>>4) & 0xff)<<24;
通过比较返回值来显示rand如何工作的示例程序。这适用于Microsoft编译(没有不匹配)。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char* argv[])
{
unsigned int seed = 1;
unsigned int rand1, rand2;
unsigned int i;
for(i = 0; i < 20; i++){
seed = seed*214013 + 2531011;
rand1 = (seed >> 16) & 0x7fffu;
rand2 = rand();
if(rand1 != rand2)
printf("mismatch %d %d\n", rand1, rand2);
}
return(0);
}
由于此版本的rand()仅返回15位种子,因此RAND_MAX将为32767或十六进制0x7fff。如wiki文章中所述,周期为2 ^ 32,这意味着种子将遍历所有4,294,967,296个可能的32位值,直到4,294,967,296调用rand()时才会重复,其中种子将循环回到1。
答案 1 :(得分:0)
现在有一个实际的问题:你不能。范围是固定的,如果您需要知道它,它由常量RAND_MAX
定义(它是[0 .. RAND_MAX]
)
如果你想要一个不同的范围,你必须自己安排,通常使用模数运算符%
和可选的偏移量...用于5
之间的随机数并9
使用
int foo = rand() % 5 + 5;
我在最近写的游戏中使用了这样的辅助函数:
int
randomNum(int min, int max)
{
static int seeded = 0;
if (!seeded)
{
seeded = 1;
srand((unsigned int)time(0));
}
return (rand() % (max-min+1)) + min;
}