Batch random function giving same first output

我怕爱的太早我们不能终老 提交于 2019-12-13 06:54:48

问题


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

set /a scramble=%random%

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

the second time it gives

23498,26374,17322

So only the first is similar.

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?


回答1:


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

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

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.

More information can be found here



来源:https://stackoverflow.com/questions/27880234/batch-random-function-giving-same-first-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!