2017-10-07 174 views
0

我想我的變量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 

對此有一個解釋?

+0

是的。這個問題每天可能會被詢問10次。您需要使用[延遲擴展](https://ss64.com/nt/delayedexpansion.html) – Squashman

+1

[批處理文件中延遲擴展的示例]的可能重複(https://stackoverflow.com/questions/10558316/example -of-延遲 - 膨脹 - 在分批文件) – Squashman

回答

1

由於延遲擴展的使用的一個例子,這裏是你修改後的代碼:

@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