相关疑难解决方法(0)

即使播种,C 中的 rand() 函数也不是随机的

这很可能是与机器有关的问题,但我无法弄清楚可能是什么问题。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char** argv) {

  srand(time(NULL));
  int r1 = rand();
  int r2 = rand();
  printf("%d %d\n", r1, r2);
}
Run Code Online (Sandbox Code Playgroud)

我编译上面的代码使用

gcc randd.c
Run Code Online (Sandbox Code Playgroud)

然后手动运行几次,第一个数字看起来非常相似,而第二个数字似乎是随机的:

1025720610 1435057801
1025737417 1717533050
1025754224 2000008299
1025771031 134999901
1025787838 417475150
Run Code Online (Sandbox Code Playgroud)

第一次调用rand()似乎与时间密切相关,并且随着时间的推移严格增加。关于为什么会发生这种情况或如何解决它的任何想法?

这发生在 OSX 10.11

c random

5
推荐指数
1
解决办法
949
查看次数

Windows上有哪些熵源?

我想在Windows上生成随机加密密钥.我在哪里可以获得熵?

我希望我的熵函数在没有网络连接的情况下工作,并且在Windows 2000及更高版本上可靠.即使是可能提供或不提供少量熵的来源也可能是有用的,因为所有来源都将汇集在一起​​.

这是我最初的功能列表:

GetCurrentProcessID, GetCurrentThreadID, GetTickCount, GetLocalTime, QueryPerformanceCounter, GlobalMemoryStatus, GetDiskFreeSpace, GetComputerName, GetUserName, GetCursorPos, GetMessageTime, GetSystemInfo, CryptGenRandom, GetProcessHandleCount, GetProcessMemoryInfo.

windows random winapi cryptography entropy

4
推荐指数
1
解决办法
5832
查看次数

C++`srand()`函数产生一个模式?

新的C++和下面的初学者的教程在这里.请参阅标题为C++中的随机数的部分.准确使用给出的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main () {
   int i,j;

   // set the seed
   srand( (unsigned)time( NULL ) );

   /* generate 10  random numbers. */
   for( i = 0; i < 10; i++ ) {
      // generate actual random number
      j = rand();
      cout <<" Random Number : " << j << endl;
   }

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我播种srand()time()(编译g++)等所产生的结果应该是完全随机的.但是,这是我得到的结果:

$ ./a.out
 Random Number : 1028986599 …
Run Code Online (Sandbox Code Playgroud)

c++ random srand

-1
推荐指数
1
解决办法
96
查看次数

标签 统计

random ×3

c ×1

c++ ×1

cryptography ×1

entropy ×1

srand ×1

winapi ×1

windows ×1