批处理随机函数给出相同的第一个输出 [英] Batch random function giving same first output

查看:79
本文介绍了批处理随机函数给出相同的第一个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的批处理程序中,我中间有这行:

In my batch program, I have this line in the middle of it:

set /a scramble=%random%

这里的问题是,每次我打开批处理文件时,它都会给我相同的输出,例如,我打开它,并将%scramble%设置为17534,下一次我打开它时,它非常相似,例如17546,少量增加.如果我循环它,那么只有第一个随机数是相似的,其余的都是随机的.

The problem here is that everytime I open the batch file, it gives me the same output, for example I open it and it sets %scramble% to 17534, the next time I open it, it is very similar, for example 17546, increasing by a small amount. If I loop it, then only the first random number is similar, all the rest are random.

例如,我第一次运行它,它给了我以下数字列表:

For example The first time I run it, it gives me this list of numbers:

23486,32645,4854

23486,32645,4854

第二次给出

23498,26374,17322

23498,26374,17322

所以只有第一个是相似的.

So only the first is similar.

一个简单的解决方法是将echo %random%cls放在批处理的开头,所以这对我来说不是问题,但我只是想知道为什么会这样?

A simple workaround is to put echo %random% and then cls in the beginning of the batch, so it's not a problem for me, but I'm just wondering why this is?

推荐答案

cmd中的随机数生成器使用当前时间(具有第二个分辨率)来播种prng.每个cmd实例都执行一次初始化.

Random number generator in cmd uses the current time (with second resolution) to seed the prng. This initialization is done once per cmd instance.

因此,如果您每次都在新的cmd实例中运行批处理文件,则种子在每种情况下都非常相似.

So, if you are running your batch file in a new cmd instance each time, the seed is very similar in each case.

但是,如果您在同一cmd实例中多次启动批处理文件,则序列将不会如此相似,因为初始化仅执行一次.

But if you start your batch file several times inside the same cmd instance, the sequences will not be so similar as the initialization is done only once.

更多信息,请参见此处

这篇关于批处理随机函数给出相同的第一个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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