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.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
Note that Windows batch files don't support floating-point arithmetic, so if an expression result is a fractional number, only the integer part will be counted. For example, 3/2 evaluates as 1 and 2/3 as 0. Show activity on this post. DON'T do maths in batch.
Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.
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%%
)
It's not doing anything because "y" is just a letter. You need percent signs to reference the variable.
set /a x = %%y/25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With