Same random numbers every time I run the program(每次运行程序时都是相同的随机数)
问题描述
我每次运行游戏时输出的随机数都以相同的顺序输出.为什么会发生这种情况?
My random numbers that output, output in the same sequence every time I run my game. Why is this happening?
我有
#include <cstdlib>
并使用它来生成随机数
randomDiceRollComputer = 1 + rand() % 6;
推荐答案
你需要为你的随机数生成器做种子:
You need to seed your random number generator:
试着把它放在程序的开头:
Try putting this at the beginning of the program:
srand ( time(NULL) );
请注意,您需要#include
.
这里的想法是在每次启动程序时为 RNG 设置不同的编号.通过使用时间作为种子,每次启动程序时您都会得到不同的数字.
The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time you launch the program.
这篇关于每次运行程序时都是相同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每次运行程序时都是相同的随机数


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09