批处理程序不断给我“缺少操作数”错误

时间:2018-10-17 18:05:59

标签: batch-file for-loop operands

当我运行假定将两个数字相除并给出输出的代码时,或者使用数字66时终止;它告诉我我缺少操作数?

@Echo off
setlocal enableextensions enabledelayedexpansion
FOR /L %%x in (1, 0, 10) DO (
Set /p "num1=Enter num1: "
if "%num1%" == "66" (
GOTO EOF
)

Set /P "num2=Enter num2: "

set /a "sum4=%num1% / %num2%"
echo result: !sum4!

if "%num2%" == "0" (
  echo Number not valid, 0 entered
) 
IF NOT "%num2%" == "0" (
  set /a "sum5=%num1% / %num2%"
  echo result: !sum5!
)
)
pause
:EOF
cls
echo Program has ended

1 个答案:

答案 0 :(得分:1)

尝试这样(我使用与您相同的逻辑):

@Echo off
setlocal enableextensions enabledelayedexpansion
FOR /L %%x in (1, 0, 10) DO (
    Set /p "num1=Enter num1: "
    if "!num1!" == "66" (
        call :END
    )

    Set /P "num2=Enter num2: "

    set /a "sum4=!num1! / !num2!"
    echo result: !sum4!

    if "!num2!" == "0" (
      echo Number not valid, 0 entered
    ) 
    IF NOT "!num2!" == "0" (
      set /a "sum5=!num1! / !num2!"
      echo result: !sum5!
    )
)
pause
exit /b
:END
cmd /k & exit

退出无限FOR /L循环不是那么容易,因此在这里我使用了exit命令,并且在同一控制台中启动了一个新的cmd进程。也许有更好的方法。

丢失操作数错误的原因是因为您并没有在需要时在所有地方都使用!进行变量扩展(尽管您已经激活了延迟扩展)