作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
大多数现代计算机都表现出不确定性行为,这使得无法判断两次连续调用读取计算机时钟之间会发生多少个时钟周期。
以下代码是使用计算机时钟的一个字节的伪随机数生成器。
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
}
除了像加密这样的严肃应用程序之外,它还可以用于游戏的移动平台。
我想知道这种实现的优点和缺点是什么。
最佳答案
您缺少使用 rand()
的正确方法,或者更具体地说,使用 srand()
。
您需要在程序运行期间精确调用srand()
一次。不要在循环中调用srand()
。不要在每次调用 rand()
之前调用 srand()
。确保正确的 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;
}
关于计算机时钟作为伪随机发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117229/
我是一名优秀的程序员,十分优秀!