我的随机数输出,每次运行我的游戏时以相同的顺序输出.为什么会这样?
我有
#include <cstdlib>
Run Code Online (Sandbox Code Playgroud)
并使用它来生成随机数
randomDiceRollComputer = 1 + rand() % 6;
Run Code Online (Sandbox Code Playgroud)
Mys*_*ial 30
您需要为随机数生成器播种:
试着把它放在程序的开头:
srand ( time(NULL) );
Run Code Online (Sandbox Code Playgroud)
请注意,您需要#include <ctime>.
这里的想法是每次启动程序时为RNG添加不同的编号.通过使用时间作为种子,每次启动程序时都会得到不同的数字.
你需要给randum号码生成器一个种子.这可以通过获取当前时间来完成,因为这有希望是某种随机的.
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int r;
srand(time(0));
r = rand();
return 0;
}
Run Code Online (Sandbox Code Playgroud)