dr_rk
dr_rk

Reputation: 4565

Arithmetic inside a for loop batch file

I have a for loop in a batch file that looks like this:

for %%y in (100 200 300 400 500) do (
    set /a x = y/25     
    echo %x%
)

The line:

set /a x = y/25

Doesn't seem to be doing any division. What is the correct syntax for dividing each y by 25? I only need the integer result from this division.

Upvotes: 8

Views: 18326

Answers (3)

George
George

Reputation: 1

I was having the same issue but turned out to be an integer issue. I was multiplying after dividing but need to before. What was happening is something like this: 1/100x100 which operates like 1\100=0 then 0x100=0 I changed it to 1x100/100 which operates like 1x100=100 then 100/100=1

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /f "usebackq" %%b in (`type List.txt ^| find "" /v /c`) do (
    set Count=%%b
    )
)
REM Echo !Count! -->Returns the correct number of lines in the file
for /F "tokens=*" %%A in (List.txt) do (
    set cName=%%A
    set /a Number+=1
    REM Echo !Number! -->Returns the correct increment of the loop
    set /a Percentage=100*!Number!/!Count!
    REM Echo !Percentage! -->Returns 1 when on the first line of a 100 line file
    set a=1
    set b=1000
    set /a c=100*1/100
    Rem -->echo c = !c! --Returns "C = 1"
)

Upvotes: 0

dbenham
dbenham

Reputation: 130929

Environment variables need not be expanded to use in a SET /A statement. But FOR variables must be expanded.

Also, even if your computation worked, the ECHO would fail because percent expansion takes place when a statement is parsed, and the entire FOR construct is parsed at once. So the value of %x% would be the value as it existed before the loop is executed. To get the value that was set within the loop you should use delayed expansion.

Also, you should remove the space before the assignment operator. You are declaring a variable with a space in the name.

@echo off
setlocal enableDelayedExpansion
for %%A in (100 200 300 400 500) do (
  set n=%%A

  REM a FOR variable must be expanded
  set /a x=%%A/25

  REM an environment variable need not be expanded
  set /a y=n/25

  REM variables that were set within a block must be expanded using delayed expansion
  echo x=!x!, y=!y!

  REM another technique is to use CALL with doubled percents, but it is slower and less reliable
  call echo x=%%x%%, y=%%y%%
)

Upvotes: 16

Nilpo
Nilpo

Reputation: 4816

It's not doing anything because "y" is just a letter. You need percent signs to reference the variable.

set /a x = %%y/25

Upvotes: 1

Related Questions