首页 > 解决方案 > 在 C 中使用 rand() 在每次运行时获取不同的数字而不使用 time() 或 getpid()?

问题描述

我目前正在使用 srand() 中的 time() 函数在每次程序运行时生成一个完全不同的随机数。

srand(time(NULL));// chooses random seed for a different rand() every run 
  int n = 1 + rand() / (RAND_MAX / (100 - 1 + 1) + 1); // only generates numbers between 1 and 100
  printf("n = %d",n);
  int a = rand();
  printf("\na = %d",a);
  int b = rand();
  printf("\nb = %d",b);

不幸的是,我了解到我不允许使用 time() 或 getpid()。有没有办法,每次运行程序时只使用 <stdio.h>, <stdlib.h> <assert.h> 生成不同的随机数?

标签: crandom

解决方案


我想有人在这里回答了你的问题: Generating random values without time.h

我认为您可以使用带有数字的文件并从那里随机选择您的数字,例如:

static int randomize_helper(FILE *in)
{
     unsigned int  seed;

    if (!in)
         return -1;

    if (fread(&seed, sizeof seed, 1, in) == 1) {
        fclose(in);
        srand(seed);
    return 0;
    }

    fclose(in);
    return -1;
}

static int randomize(void)
{
    if (!randomize_helper(fopen("/dev/urandom", "r")))
         return 0;
    if (!randomize_helper(fopen("/dev/arandom", "r")))
         return 0;
    if (!randomize_helper(fopen("/dev/random", "r")))
         return 0;

/* Other randomness sources (binary format)? */

/* No randomness sources found. */
    return -1;
}

这是主要的一个例子:

 int main(void)
 {
    int I;

    if (randomize())
        fprintf(stderr, "Warning: Could not find any sources for randomness.\n");

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

    return EXIT_SUCCESS;
}

推荐阅读