For Loop on Windows Batch

2019-03-03 12:49发布

I am doing some batch practice and I am trying to do a loop to go backwards and count the numbers from 110 to 100, but only the even numbers. I almost got it to work, but for some reason totalCount is not updating every time the for loop goes around. At the end it prints the total as 100 which is simply the last number of the loop. What am I doing wrong?

::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%

2条回答
我命由我不由天
2楼-- · 2019-03-03 13:20

Try changing %totalCount% to !totalCount!. Therefore, the code should look like this:

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!
查看更多
聊天终结者
3楼-- · 2019-03-03 13:28

There are several correct ways to do this and one wrong way. The bad way is this:

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

Because %totalCount% is expanded just once, before the for is executed, so the value of the sum is always 0 plus each term.

One possible solution is use Delayed Expansion as Dale suggested:

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%

This way, the value of !totalCount! is correctly replaced in each for cycle. However, this is not needed either, because set /A command takes the current value of the variables by itself each time it is executed:

echo off

set /a totalCount = 0

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

echo total is %totalCount%

Moreover, set /A command have a way to increment a variable that don't even requires to write its name, so the matter of this discussion completely dissapear:

echo off

set /a totalCount = 0

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

echo total is %totalCount%
查看更多
登录 后发表回答