2013-12-12 156 views
0

我正在做一些批處理練習,我試圖做一個循環倒退,並計數從110到100,但只有偶數。我幾乎可以開始工作,但出於某種原因,每次執行for循環時都不會更新totalCount。最後它打印總數爲100,這只是循環的最後一個數字。我究竟做錯了什麼?For Windows在Windows批處理

::echo off 
setlocal enableextensions 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = %totalCount% + %%x 
) 

echo total is %totalCount% 

回答

1

嘗試改變%totalCount%!totalCount!。因此,代碼應該是這樣的:

echo off 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = !totalCount! + %%x 
) 

echo total is !totalCount! 
4

有幾個正確方法可以做到這一點,一個錯誤方式。糟糕的方法是這樣的:

for /l %%x in (110, -2, 100) do (
    set /a totalCount = %totalCount% + %%x 
) 

因爲%totalCount%擴大只是一次,在執行之前for,所以和的值始終爲0加上每學期。

一種可能的解決方案是使用延遲擴展作爲戴爾建議:

echo off 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = !totalCount! + %%x 
) 

echo total is %totalCount% 

這樣,!totalCount!值在每個週期for正確替換。然而,這是沒有必要要麼,因爲set /A命令本身每次執行時間花費的變量當前值:

echo off 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = totalCount + %%x 
) 

echo total is %totalCount% 

此外,set /A命令有辦法增量變動的變量,唐甚至不需要寫出它的名字,所以這個討論的問題完全消失了:

echo off 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount += %%x 
) 

echo total is %totalCount%