C中的rand()问题

akw*_*way 4 c random gcc

可能重复:
为什么我总是使用rand()得到相同的随机数序列?

到目前为止这是我的文件:

#include <stdio.h>

int main(void) {
    int y;
    y = generateRandomNumber();
    printf("\nThe number is: %d\n", y);
    return 0;
}

int generateRandomNumber(void) {
    int x;
    x = rand();
    return x;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是rand()总是返回41.我在win上使用gcc ...不知道该怎么做.

编辑:使用时间生成随机数将无法正常工作.它为我提供了一个数字(12000),每次我调用它只是稍微高一点(大约每秒+3).这不是我需要的随机性.我该怎么办?

Ste*_*eve 8

你需要提供种子.

来自网络 -

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

int main(void)
{
  int i, stime;
  long ltime;

  /* get the current calendar time */
  ltime = time(NULL);
  stime = (unsigned) ltime/2;
  srand(stime);

  for(i=0; i<10; i++) printf("%d ", rand());

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

  • 请注意,时间(NULL)通常足够好,但是在某些情况下您需要更多的熵,因此您需要做更多的工作来提出足够好的种子.对我来说,为了生成良好的伪随机数(来自rand()的输出),我总是觉得很奇怪,你首先需要提出一个好的伪随机数(种子). (2认同)
  • @Graeme - 在那种情况下你要找的是"Catch-22". (2认同)

Dan*_*ker 8

标准技巧是:

srand(time(0));  // Initialize random number generator.
Run Code Online (Sandbox Code Playgroud)

注意:该功能srand不是rand.

在您的main功能中执行此操作一次.之后,只打电话rand来获取号码.

根据实现,它还可以帮助获取和丢弃一些结果rand,以允许序列偏离种子值.