【发布时间】:2020-11-04 12:24:22
【问题描述】:
我正在尝试使用 rand() 生成一个随机数序列。 我有这样的事情:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Random(int min, int max)
{
/* returns a random integer in [min, max] */
double uniform; // random variable from uniform distribution of [0, 1]
int ret; // return value
srand((unsigned int)clock());
uniform = rand() / (double)RAND_MAX;
ret = (int)(uniform * (double)(max - min)) + min;
return ret;
}
int main(void)
{
for(int i=0; i<10; i++)
printf("%d ", Random(0, 100));
printf("\n");
return 0;
}
在 macOS v10.14 (Mojave) 和 Ubuntu 18.04 (Bionic Beaver) 上执行时会产生不同的结果。
它适用于 Ubuntu:
76 42 13 49 85 7 43 28 15 1
但不是在 macOS 上:
1 1 1 1 1 1 1 1 1 1
为什么它在 macOS 上不能正常工作?随机数生成器有什么不同吗?
【问题讨论】:
-
你必须调用 srand() 一次:stackoverflow.com/questions/46877089/…
-
另外,
clock()通常是从程序执行开始的计数。将time()传递给srand()更为常见。 C18 标准提到了clock()7.27.2.1 实现对程序使用的处理器时间的最佳近似,因为实现定义的时代开始时仅与程序相关调用。 -
我觉得
clock()这个函数在macos上表现的很奇怪,能不能每次用的时候显示一下它的值? -
见srand() — why call it only once?。而且mac上的
rand()太烂了,你应该用arc4random()代替,见Why does rand() % 7 always return 0?,Rand() % 14 only generates the values 6 or 13 -
除了其他 cmets,您的 Mac 实现的运行速度可能比您的 ubuntu 实现快得多。也许您正在 Mac 上的虚拟机中运行 ubuntu?