For Loop on Windows Batch

前端 未结 2 1026
别跟我提以往
别跟我提以往 2021-01-29 05:33

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 so

相关标签:
2条回答
  • 2021-01-29 06:13

    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%
    
    0 讨论(0)
  • 2021-01-29 06:19

    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!
    
    0 讨论(0)
提交回复
热议问题