3

使用 .bat 文件,我知道如何用 %Random% 回显一个随机数。如何设置 %Random% 的某个随机范围,例如 50-100?哦,我有一个在开始时声明的积分系统: SET /A MAINSCORE=0 我如何设置随机范围数以从 MainScore 中添加/减去?谢谢。

4

4 回答 4

7

%RANDOM%返回一个介于 0 和 32767 之间的数字。要缩小这些范围,请使用模运算符,并使用加法或减法来抵消结果。例子:

@set /a bottomlimit = 50
@set /a upperlimit = 100
@set /a result = %bottomlimit% + %RANDOM% %% (%upperlimit% - %bottomlimit% + 1)
@echo %result%
于 2013-08-21T23:56:55.983 回答
1
@echo off
set min=5
set max=10
set /a range=max-min +1
set /a rnd=%random% %%%range% +%min%
echo %rnd%
pause

就我个人而言,我真的很喜欢我的做法,
这将通过 5 到 10 之间的任何 #
,最重要的是,它很干净。谢谢你

于 2016-02-02T22:20:20.910 回答
0

this should help:

# If you need a random int within a certain range, use the 'modulo' operator.
# This returns the remainder of a division operation.

RANGE=500

echo

number=$RANDOM
let "number %= $RANGE"
#           ^^
echo "Random number less than $RANGE  ---  $number"

#  If you need a random integer greater than a lower bound,
#+ then set up a test to discard all numbers below that.

FLOOR=200

number=0   #initialize
while [ "$number" -le $FLOOR ]
 do
  number=$RANDOM
done
echo "Random number greater than $FLOOR ---  $number"
echo

# Let's examine a simple alternative to the above loop, namely
#       let "number = $RANDOM + $FLOOR"
# That would eliminate the while-loop and run faster.
# But, there might be a problem with that. What is it?

# Combine above two techniques to retrieve random number between two limits.
number=0   #initialize
while [ "$number" -le $FLOOR ]
  do
    number=$RANDOM
    let "number %= $RANGE"  # Scales $number down within $RANGE.
  done
echo "Random number between $FLOOR and $RANGE ---  $number"

Taken from here: http://tldp.org/LDP/abs/html/randomvar.html

Then, once you have the $number, you can just do something like: num=expr $number + $MAINSCORE

Hope that helps.

于 2013-08-21T23:48:21.670 回答
0

简单的程序,可让您为易于选择的程序设置数字量...

:loop
cls
goto before

:before
@echo off
setlocal delayexpansion
cls
@mod con: clos=80 lines=25
title Number Picker
color 0a
cls
goto menu

:menu
cls
echo.
echo Number Picker
echo.
set/p input= "Number: "
if %input%== goto show

:show
set /a bottomlimit = 0
set /a upperlimit = %input%
set /a result = %bottomlimit% + %random% %% (%upperlimit% - %bottomlimit% +1)
echo.
echo Random Number: %result%
echo.
echo Press 'Y' to close press 'N' to go to menu...
echo.
set/p input= "Exit: "
if %input%==y exit
if %input%==n goto loop
于 2017-08-10T23:39:48.740 回答