【问题标题】:I'm trying to create a "command" for command prompt that creates a random number我正在尝试为创建随机数的命令提示符创建一个“命令”
【发布时间】:2014-07-25 20:55:03
【问题描述】:

我的代码是

   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之间的随机数。请帮忙,我不知道它有什么问题。抱歉,如果这似乎难以理解。

【问题讨论】:

  • 你设置了 /a heh=,你打算把 /a 放在那里吗?
  • @IrishGeek82:是的,/a 必须在那里进行算术运算,而不是将变量设置为字符串(请参阅set /?
  • 基本问题是setcommand 中的关闭) 被解释为ifstatement 的关闭)。所以/ 被解释为下一个命令——当然会失败。 Rafaels 答案在任何 ifblocks 之外使用 set 命令,Adils 答案使用封闭 "setcommand 来告诉解析器整个事物属于 set
  • 您不必检查所有三个参数是否存在。如果第三个存在,则前两个不能为空。只需检查%3。如果存在,你知道%1%2也必须存在。

标签: windows batch-file terminal


【解决方案1】:
@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

【讨论】:

  • @tatatat0,它们不是必需的,但是,您尝试过使用它们吗?你执行过发布的代码吗?
【解决方案2】:

好吧,试试这段代码

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 无效。

【讨论】:

  • set %1=0 不会尝试设置%1%1 被解析(在这种情况下为randomvalue),所以它被执行为set randomvalue=0
【解决方案3】:

我喜欢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2019-07-04
    • 1970-01-01
    • 2011-12-05
    • 2021-06-25
    • 1970-01-01
    • 2020-05-09
    • 2021-08-09
    相关资源
    最近更新 更多