c - 在 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> 生成不同的随机数?
解决方案
我想有人在这里回答了你的问题: 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;
}
推荐阅读
- javascript - 从 Google 表格中删除多列,避免昂贵的循环
- sql - 需要有关如何分组此表的想法
- css - Boostrap 4 中的嵌套 CSS 失败
- php - 通过循环创建字段并使用 vars - WordPress Customizer
- azure - 创建 Azure 应用服务时的 2 个订阅“Microsoft Azure”和“按需付费”,选择哪一个来托管共享点远程事件接收器
- html - 容器流体中的 d-flex 类,使其内部的 h1 更小
- code-composer - 无法运行任何 eclipse 命令从命令行导入或构建项目 Code Composer Studio v9.0.0
- c++ - CRTP接口:实现中的不同返回类型
- javascript - 无法访问 React js 组件的传递值
- apache-flink - MapState 不会在 Flink java 中使用 EventTimeSessionWindows 存储上一个会话