Linux Dunce
Linux Dunce

Reputation: 11

For loop not working properly? What did I do wrong?

I'm not sure what's wrong the expected output is "0 5 25 100".

The output I get is "20 3 15 60":

http://imgur.com/gallery/qBlt3

http://hastebin.com/tibirakoni.dos

@echo off
setlocal EnableDelayedExpansion  
cls  
:vars  
set numbercheck=50  
set number2=0  
set number3=0  
set number4=0  
:calc  
for %%a in (0, 1, 100) do (  
    if !numbercheck GEQ 10 (  
        set /a numbercheck= !numbercheck! - 10  
        set /a number2= !number2! +1  
        set /a number3= !number3! +5  
        set /a number4= !number4! +20  
    )  
)  
goto echo  
:echo  
echo !numbercheck!  
echo !number2!  
echo !number3!  
echo !number4!  
pause

Upvotes: 1

Views: 48

Answers (1)

DavidPostill
DavidPostill

Reputation: 7921

I'm not sure what's wrong - the expected output is 0 5 25 100

The output I get is 20 3 15 60

...

for %%a in (0, 1, 100) do (  
    if !numbercheck GEQ 10 (

...

There are two mistakes in the above code:

  1. Missing /l in the for command, it should be:

    for /l %%a in (0, 1, 100) do (
    

    Without the /l the for loop will return 0,1,100 and will only loop 3 times. With the /l the for loop will return 1,2,3,...,100

  2. Missing ! in the if command, it should be:

    if !numbercheck! GEQ 10 (
    

Corrected batch file:

@echo off
setlocal EnableDelayedExpansion  
cls  
:vars  
set numbercheck=50  
set number2=0  
set number3=0  
set number4=0  
:calc  
for /l %%a in (0, 1, 100) do (  
    if !numbercheck! GEQ 10 (  
        set /a numbercheck= !numbercheck! - 10  
        set /a number2= !number2! +1  
        set /a number3= !number3! +5  
        set /a number4= !number4! +20  
    )  
)  
goto echo  
:echo  
echo !numbercheck!  
echo !number2!  
echo !number3!  
echo !number4!  
pause

Example output:

0
5
25
100
Press any key to continue . . .

Further Reading

Upvotes: 2

Related Questions