我的代码是
IF "%1" == "-?" ( start randomhelp.bat ) IF NOT DEFINED %1 (goto notdefined) ELSE ( IF NOT DEFINED %2 (goto notdefined) ELSE ( IF NOT DEFINED %3 (goto notdefined) ELSE ( set %1=0 set /a heh=%random% * (%3 - %2 + 1) / 32768 + %2 setx %1=%heh% ) ) :notdefined
然而,每当我尝试运行它时/表示/此时是意料之外的,但是除了等式之外我没有/。我想要做的就是当你输入类似的内容时这样做
随机随机值1 50
它会将环境变量randomvalue设置为1到50之间的随机数。请帮助,我不知道它有什么问题。很抱歉,这似乎很难理解。
答案 0 :(得分:0)
好吧,试试这段代码
IF "%1" == "-?" (
start randomhelp.bat)
IF "%1" == "" (goto notdefined)
IF "%2" == "" (goto notdefined)
IF "%3" == "" (goto notdefined)
set /a heh=%random% * (%3 - %2 + 1)
set /a heh=heh / 32768 + %2
:notdefined
提示:不允许修改参数,因此set %1=0
无效。
答案 1 :(得分:0)
我喜欢@Rafael编写代码的方法,因为它避免了嵌套的IF。无论如何,要做到这一点有两件事:
REM You are missing the final parenthesis. Add that!
REM Your second IF statement should be on another line. It could be b/c of copy/paste.
REM Quote the whole expression to avoid that error
IF "%1" == "-?" (
start randomhelp.bat
)
IF NOT DEFINED %1 (goto notdefined) ELSE (
IF NOT DEFINED %2 (goto notdefined) ELSE (
IF NOT DEFINED %3 (goto notdefined) ELSE (
set %1=0
set /a "heh=%random% * (%3 - %2 + 1) / 32768 + %2"
setx %1=%heh%
)))
:notdefined
答案 2 :(得分:0)
@echo off
:: check for help request
if "%~1"=="-?" goto :showHelp
:: check if we have at least three arguments
if "%~3"=="" goto :notDefined
:: check if the second and third arguments are numeric.
for /f "delims=0123456789" %%a in ("%~2") do goto :badArguments
for /f "delims=0123456789" %%a in ("%~3") do goto :badArguments
:: calculate the random value and assign it to exit variable
set "%~1="
set /a "%~1=(%random% %% (%~3 - %~2 + 1)) + %~2" 2>nul
:: if variable does not contain any value, bad data has been
:: feed into script
if not defined %~1 goto :badArguments
goto :eof
:showHelp
echo Usage: %~n0 varName lowValue highValue
goto :eof
:notDefined
echo error: arguments missing
goto :eof
:badArguments
echo error: wrong data in arguments
goto :eof