C++随机函数返回相同的数字

Via*_*iuk -5 c++ random

我试图在0到3的范围内得到随机数.使用这样的代码:

#include <cstdlib>
int index = rand() % 3;
Run Code Online (Sandbox Code Playgroud)

但总是得到相同的结果:1 1 0 1.

我做错了什么?总是相同的数字.结果应在每次编译后或运行时更改其值?

小智 6

你忘记了广告

#include <ctime>
srand(time(NULL)) 
Run Code Online (Sandbox Code Playgroud)

在你的计划开始时.

每次根据当前时间运行程序时,这将生成一个新种子.