gpt4 book ai didi

c - rand() 函数每次产生相同的输出 C

转载 作者:行者123 更新时间:2023-11-30 14:41:39 35 4
gpt4 key购买 nike

我正在尝试使用 rand() 生成从 0 到 3 的随机数功能,并且工作正常,但我注意到一些奇怪的事情。

每次我运行和重新运行项目时,该函数都会生成相同的数字模式。

这是我正在使用的代码,尽可能简单地分解..

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

int main()
{
int randomNumber;

for (int i = 0; i < 15; i++)
{
randomNumber = rand() % 4;
printf("%d ", randomNumber);
}

getchar();
return 0;
}

这会打印 15 个从 0 到 3 的随机数,对我来说这就是我得到的

1 3 2 0 1 0 2 2 2 0 1 1 1 3 1

所以这很好。但问题是,每次我运行该程序时都会打印完全相同的内容。

知道为什么会发生这种情况吗?

最佳答案

计算机科学中不存在随机数这样的东西。因此,为了生成不同的输出,我们必须使用伪随机。为此,请在声明变量的位置写入 srand(time(0))

关于c - rand() 函数每次产生相同的输出 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54847461/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com