在Windows批处理文件中生成0-9的随机数

时间:2012-07-26 23:42:06

标签: windows batch-file cmd

我正在尝试编写一个Windows批处理文件,该文件将生成0到9之间的随机数,然后根据随机数在我们的游戏服务器中加载不同的地图列表。

我试图修改此论坛上用于生成随机字符的类似文件,但是当我将maxchars变量减少为1时。

我有时会得到@echo is off作为回复,有时会得到一个数字。

这就是我所拥有的:

@echo off & setlocal EnableDelayedExpansion
REM Random.bat
REM
REM Change these values to whatever you want, or change the code to take them
REM as command-line arguments.  You must set CHARS_LEN to the string length
REM of the string in the CHARS variable.
REM 
REM This script generates a string of these characters at least
REM MIN_CHARS_IN_LINE chars long and at most MAX_CHARS_IN_LINE chars long.

SET CHARS=0123456789
SET /A CHARS_LEN=10 + 10 + 10
SET /A MIN_CHARS_IN_LINE=1
SET /A MAX_CHARS_IN_LINE=2

REM Pick a random line length and output a random character until we reach that
REM length.

call:rand %MIN_CHARS_IN_LINE% %MAX_CHARS_IN_LINE%
SET /A LINE_LENGTH=%RAND_NUM%

SET LINE=
    for /L %%a in (1 1 %LINE_LENGTH%) do (
    call:rand 1 %CHARS_LEN%
    SET /A CHAR_INDEX=!RAND_NUM! - 1
    CALL SET EXTRACTED_CHAR=%%CHARS:~!CHAR_INDEX!,1%%
    SET LINE=!LINE!!EXTRACTED_CHAR!    
)
echo !LINE!

goto:EOF

REM The script ends at the above goto:EOF.  The following are functions.

REM rand()
REM Input: %1 is min, %2 is max.
REM Output: RAND_NUM is set to a random number from min through max.
:rand
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto:EOF

:eof

一旦我能够可靠地选择字符,我只需要在末尾添加一个选择过程,它将使用不同的命令行为每个地图列表调用服务器。

3 个答案:

答案 0 :(得分:3)

使用SET中的随机字符串,然后删除除最后一个字符之外的所有内容。

    SET RAND=%RANDOM:~-1%

答案 1 :(得分:3)

LastStar007方法适用于0到9之间的值。对于更通用的解决方案,返回0到 n 之间的伪随机数,只需使用SET / A获取%random%modulo(的n + 1)。

例如,要在命令行上获取0到9之间的随机数,请使用

set /a "rand=%random% % 10"

如果在批处理文件中使用,则模数运算符必须加倍

set /a "rand=%random% %% 10"

答案 2 :(得分:0)

如果问题仍然存在,请尝试以下操作。它会生成ab之间的数字。根据您的需要调整它:

@echo off   
color 02  
echo enter value of A  
set  /p a=  
echo.  
echo  enter value of B  
set /p b=  
:main  
set no=%random%  
if  %no% GEQ %a% goto sub  
if not %no% GEQ %a% goto  main  
:sub  
if %no% LEQ  %b% goto end  
if not %no% LEQ  %b% goto  main  
:end      
echo %no%  
goto main