-4

大多数现代计算机都表现出非确定性行为,这使得无法判断两次连续调用以读取计算机时钟之间会发生多少时钟周期。

下面的代码是一个使用计算机时钟的一个字节的伪随机数生成器。

unsigned long occurrences = 0;
unsigned long total = 0;

while (true) {
    if ((clock() & 0xFF) == 60) // testing ocurrences for a given number, 60 for instance
        occurrences++;
    total++;
    printf("%f\n", (float)occurrences / (float)total ); // this should be approximately 1/256 = 0.00390625
}

不包括诸如加密之类的严肃应用,它可以用于游戏的移动平台。

我想知道这种实施的优点和缺点是什么。

4

2 回答 2

1

您应该使用联合而不是这样的指针来进行“拆分”。

我同意随机数和时钟是两个完全不同的东西,你的陈述比提问更多。

于 2013-01-02T09:30:10.490 回答
1

您缺少正确的使用方式,rand()或者更具体地说,srand().

您需要srand()在程序运行期间只调用一次。不要srand()循环调用。不要srand()在每次调用之前调用rand()。确保正确srand()管理的最好方法是在你的函数中调用它一次main(),然后忘记它:rand()以后再使用。

#include <stdlib.h> /* rand, srand */
#include <time.h>   /* time */

int main(void) {
    /* initialization */
    srand(time(NULL));

    /* input, possibly calling rand() */

    /* process, possibly calling rand() */

    /* output, possibly calling rand() */

    /* termination */
    return 0;
}
于 2013-01-02T10:21:57.620 回答