需要一些快速帮助。这是一个大学程序,一切都工作正常,除了当我调用 :forLoop 方法来迭代 100 个数字 (1,1,100) 时,从 1 开始,一直到 1 直到 100 并进行迭代 % 5 (i%%5)。由于某种原因我无法让它工作。感谢任何帮助或指导。
当我 echo %%A 时,它正在迭代所有完美的数字。当我 echo %result% 时,我得到一个空白“”(里面什么也没有)
:forLoop
FOR /L %%A IN (1,1,100) DO (
set /A result=%%A %% 2
echo "%%A"
echo "%result%"
)
正确的代码是
:forLoop
setlocal ENABLEDELAYEDEXPANSION
FOR /L %%A IN (1,1,100) DO (
set /A result=%%A %% 5
echo !result! >> results.txt
set /A total=!total!+!result!
echo !total!
)
最佳答案
问题在于,当读取for
时,%result%
被替换,这意味着执行循环时它不再是变量。您需要的是启用延迟变量扩展,然后使用 !
而不是 %
:
setlocal ENABLEDELAYEDEXPANSION
:forLoop
FOR /L %%A IN (1,1,100) DO (
set /A result=%%A %% 5
echo "%%A"
echo !result!
)
这一切都在运行 SET/?
时收到的帮助消息中进行了解释:
Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion: set VAR=before if "%VAR%" == "before" ( set VAR=after if "%VAR%" == "after" @echo If you see this, it worked ) would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected: set LIST= for %i in (*) do set LIST=%LIST% %i echo %LIST% in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is: for %i in (*) do set LIST= %i which just keeps setting LIST to the last file found. Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended: set VAR=before if "%VAR%" == "before" ( set VAR=after if "!VAR!" == "after" @echo If you see this, it worked ) set LIST= for %i in (*) do set LIST=!LIST! %i echo %LIST%
关于Windows 批处理脚本 - For/L 不起作用 - 简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827461/