for循环批处理文件中的算术

dr_*_*_rk 6 cmd batch-file

我在批处理文件中有一个for循环,如下所示:

for %%y in (100 200 300 400 500) do (
    set /a x = y/25     
    echo %x%
)
Run Code Online (Sandbox Code Playgroud)

这条线:

set /a x = y/25
Run Code Online (Sandbox Code Playgroud)

似乎没有进行任何划分.将每个y除以25的正确语法是什么?我只需要这个分区的整数结果.

dbe*_*ham 12

无需扩展环境变量即可在SET/A语句中使用.但必须扩展FOR变量.

此外,即使您的计算有效,ECHO也会失败,因为在解析语句时会发生百分比扩展,并且会立即解析整个FOR构造.因此%x%的值将是执行循环之前存在的值.要获得在循环中设置的值,您应该使用延迟扩展.

此外,您应该在赋值运算符之前删除空格.您正在声明名称中带有空格的变量.

@echo off
setlocal enableDelayedExpansion
for %%A in (100 200 300 400 500) do (
  set n=%%A

  REM a FOR variable must be expanded
  set /a x=%%A/25

  REM an environment variable need not be expanded
  set /a y=n/25

  REM variables that were set within a block must be expanded using delayed expansion
  echo x=!x!, y=!y!

  REM another technique is to use CALL with doubled percents, but it is slower and less reliable
  call echo x=%%x%%, y=%%y%%
)
Run Code Online (Sandbox Code Playgroud)