我有一个值,我想用随机数和一些if语句来改变。
@echo off
set ethercost=275
:screen1
echo %ethercost%
set /p c=
if "%c%" == "1" goto timejump
:timejump
set /a num=%random% %% 6
if %num%==0 %ethercost%-=20
if %num%==1 %ethercost%-=10
if %num%==2 %ethercost%-=5
if %num%==4 %ethercost%+=5
if %num%==5 %ethercost%+=10
if %num%==6 %ethercost%+=20
goto screen1
我想根据随机数更改ethercost(如果num = 1,则ethercost减少10) 谁知道我怎么能这样做?
答案 0 :(得分:2)
你需要利用这个:
if %num%==0 set /a ethercost -= 20
if %num%==1 set /a ethercost -= 10
if %num%==2 set /a ethercost -= 5
if %num%==4 set /a ethercost += 5
if %num%==5 set /a ethercost += 10
if %num%==6 set /a ethercost += 20
答案 1 :(得分:0)
在您的代码中,您忘记了set /A
命令,并且必须包含没有百分号的变量 name (因为%ethercost%
是变量 value );那就是:
if %num%==0 set /A ethercost-=20
然而,这个问题是一个很好的例子,介绍一个常用的概念叫做 array 。它的用法非常简单,我不会包含大量的解释,只是代码中的一个小注释:
@echo off
rem Define the increments per value array
set increment[0]=-20
set increment[1]=-10
set increment[2]=-5
set increment[3]=5
set increment[4]=10
set increment[5]=20
set ethercost=275
:screen1
echo %ethercost%
set /p c=
if "%c%" == "1" goto timejump
goto :EOF
:timejump
set /a num=%random% %% 6
set /a ethercost+=increment[%num%]
goto screen1
您可以在this Wikipedia article中阅读有关数组概念的详细说明,并详细说明其在this post的批处理文件中的使用。