srand()——为什么只调用一次? [英] srand() — why call it only once?

查看:38
本文介绍了srand()——为什么只调用一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于这个问题的评论推荐的srand初始化方式?第一条评论说srand() 应该在应用程序中只调用一次.为什么会这样?

This question is about a comment in this question Recommended way to initialize srand? The first comment says that srand() should be called only ONCE in an application. Why is it so?

推荐答案

这取决于您要实现的目标.

That depends on what you are trying to achieve.

随机化作为具有起始值的函数执行,即种子.

Randomization is performed as a function that has a starting value, namely the seed.

因此,对于相同的种子,您将始终获得相同的值序列.

So, for the same seed, you will always get the same sequence of values.

如果每次需要随机值时都尝试设置种子,并且种子是相同的数字,那么您将始终获得相同的随机"值.

If you try to set the seed every time you need a random value, and the seed is the same number, you will always get the same "random" value.

seed 通常取当前时间,也就是秒,如time(NULL),所以如果你总是在取随机数之前先设置seed,会得到同样的数字只要您在同一秒内多次调用 srand/rand 组合.

Seed is usually taken from the current time, which are the seconds, as in time(NULL), so if you always set the seed before taking the random number, you will get the same number as long as you call the srand/rand combo multiple times in the same second.

为了避免这个问题,每个应用程序只设置一次 srand,因为两个应用程序实例是否会在同一秒被初始化是值得怀疑的,所以每个实例都会有不同的随机数序列.

To avoid this problem, srand is set only once per application, because it is doubtful that two of the application instances will be initialized in the same second, so each instance will then have a different sequence of random numbers.

但是,您可能会在一秒钟内多次运行您的应用程序(特别是如果它很短,或者命令行工具或类似的东西),那么您将不得不求助于其他方式选择种子(除非您可以在不同的应用程序实例中使用相同的序列).但就像我说的,这取决于您的应用程序使用上下文.

However, there is a slight possibility that you will run your app (especially if it's a short one, or a command line tool or something like that) many times in a second, then you will have to resort to some other way of choosing a seed (unless the same sequence in different application instances is ok by you). But like I said, that depends on your application context of usage.

此外,您可能想尝试将精度提高到微秒(最小化相同种子的机会),需要 (sys/time.h):

Also, you may want to try to increase the precision to microseconds (minimizing the chance of the same seed), requires (sys/time.h):

struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);

这篇关于srand()——为什么只调用一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆