c - 随机函数如何在 C 中真正起作用?
问题描述
我的程序每次运行时都会返回相同的值:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int randomNum = rand() % 100;
printf("random number: %d", randomNum);
}
为什么会这样,我该如何解决?
解决方案
这是因为rand
它是一个伪随机数生成器,这意味着它为任何给定的输入返回相同的序列(输入默认为 1)。
您可以在每次运行程序时为随机数生成器播种时间以获得不同的值:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct timespec ts;
timespec_get(&ts, TIME_UTC);
srand(ts.tv_sec ^ ts.tv_nsec);
int random_num = rand() % 100;
printf("random number: %d", random_num);
}
如果您有 POSIX,您还可以添加一个+ getpid()
tosrand
的参数和#include <stdlib.h>
.
推荐阅读
- sql - T-SQL 查询以汇总每年每月的总金额以及迄今为止的累计金额
- linux - 如何检测是否正在运行 i3-wm 或 GNOME 是否正在 bash 中运行
- c++ - 类中的 C++ 字符串在构造后变为空
- maven - 从 GitHub Maven Package Repo 下载包会导致 400 错误
- java - Javadoc:{@code ...} 可以换行吗?
- windows - 批处理文件复制文件,如果文件存在重命名带有时间戳的文件
- javascript - 用户可以在 React DevTools 中编辑状态吗?
- docker - Hadoop“copyFromLocal:无法从空字符串创建路径”错误
- r - r curl::curl_fetch_memory(url,handle = h)中的 Blastula 错误:MAIL 失败:530
- google-sheets-api - 我可以让用户从静态网站的*他*的谷歌电子表格中写入/读取数据吗?