Random Variables in Batch Files
batch-file, random
Solution
EDIT: I changed my answer because the OP changed his question: originally the range of desired random numbers was 0 to 4...
The right formula is:
set /a var=%random% * 4 / 32768
The use of other operators instead (like / or %) modify random number distribution, so you will get a repeated result more frequently than with the right formula.
EDIT: Additional explanations added
Previous code should correctly works in your example above. However, if your code is placed inside a code block (enclosed in parentheses), then you must use Delayed Expansion (as other people indicated in their answers) in all variables that may be modified inside the block, including RANDOM. For example:
@echo off
setlocal EnableDelayedExpansion
:ProgStart
(
set /a var = !random! * 4 / 32768
goto target!var!
)
If you wish, you may use this simpler formula that gives equivalent results (random numbers between 0 and 3):
set /a var = !random! / 8192
Problem
I am trying to create a random variable between 0 and 3 with a batch file. Right now I have the following code: ``` @echo off set /a var=%random%/8192 @echo %var% Pause ``` This batch file returns "2" every time. If I type the same commands into the command line directly it returns 0 through 3. Any related knowledge would be appreciated :)