且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么每次编译和运行 rand() 都会得到相同的结果?

更新时间:2023-11-20 20:07:22

在使用 rand 函数之前,您需要为其设置一个唯一编号.最简单的方法是使用 time()

You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

例如

srand(time(NULL));
rand();//now returns a random number

原因是 rand()(或任何其他基于算法的函数)提供的随机数不是随机的.rand 函数只是获取其当前的数值状态,应用转换,将转换结果保存为新状态并返回新状态.

The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

所以为了让 rand 返回不同的伪随机数,你首先必须将 rand() 的状态设置为唯一的.

So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.