Reputation: 33
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 :)
Upvotes: 3
Views: 16191
Reputation: 101
The actual command you want is:
set /a var=%random% %% 4
This will give you: 0, 1, 2 or 3.
If you are doing this inside a FOR-loop use !..!-type variable instead of %..%-type variables in which case you will also need setlocal enabledelayedexpansion
somewhere near the beginning of your batch file.
Upvotes: 2
Reputation: 67216
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
Upvotes: 3
Reputation: 24466
Your code is fine. I have a suspicion though. In your full script, do you set var
and check its value within a for
loop or if
statement? If so, when you check the value of %var%
the result is whatever your script inherited as the environment variable %var%
's value, probably a holdover from your command line testing outside the script.
If my assessment is true, then you need a setlocal enabledelayedexpansion
and echo !var!
. Otherwise for
or if
will evaluate %var%
with the value it contained at the time for
or if
was first encountered.
Upvotes: 1
Reputation: 3900
Modulo works pretty well in this situation:
set /a ran=%random% %% 4 + 1
Would set %ran%
to a number between 1 and 4. However, that only works in a batch file.
On the command prompt, you would need:
set /a num=%random% % 4 + 1
Upvotes: 1
Reputation: 37569
I think, you use %random% inside an if
or for
code block. In this case you need delayed expansion
and !variables! instead of %variables%. Example:
@echo off & setlocal enabledelayedexpansion
for /l %%i in (1,1,5) do (
echo %random% !random!
)
Upvotes: 1