为什么环境变量没有在循环中更新?
问题描述:
我想我的变量res
在循环内更新,但它不会更新,直到第二次迭代。为什么环境变量没有在循环中更新?
这里是我的代码:
@echo off
set /a res=10
:loop
if %res% gtr 100 (
goto endLoop
) else (
set /a res=res*10
rem Here the 'res' shouldn't it be 100?
echo the result is : %res%
rem Here the first iteration display 10 not 100.
goto loop
)
:endLoop
pause > nul
对此有一个解释?
答
由于延迟扩展的使用的一个例子,这里是你修改后的代码:
@Echo Off
SetLocal EnableDelayedExpansion
Set "res=10"
:loop
If %res% Lss 100 (
Set/A res*=10
Echo the result is : !res!
GoTo loop
)
Pause>Nul
有没有在这种情况下使用延迟扩展的选择,但我建议你坚持前者,直到你有信心足以理解事物被读取和解析的顺序:
@Echo Off
Set "res=10"
:loop
If %res% Lss 100 (
Set/A res*=10
Call Echo the result is : %%res%%
GoTo loop
)
Pause>Nul
是的。这个问题每天可能会被询问10次。您需要使用[延迟扩展](https://ss64.com/nt/delayedexpansion.html) – Squashman
[批处理文件中延迟扩展的示例]的可能重复(https://stackoverflow.com/questions/10558316/example -of-延迟 - 膨胀 - 在分批文件) – Squashman