1

I have a value I want to change with a random number and some if statements.

@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

I want to change ethercost based on the random number (if num=1, ethercost goes down by 10) Anyone know how I could do this?

  • 1
    you need to describe what you want to achieve, (check,) and you need to show what you have tried so far, (check,) but then you also need to explain precisely what results you get, and precisely what results you expected instead. Right now you are asking a question of how to do something, and you are showing some code which, as far as we can tell, should be achieving that something, so it is entirely unclear what you are asking. – Mike Nakis Jul 11 '17 at 10:37
  • Oh, sorry. With the methods I've tried, I have only gotten 275 each time I tried to repeat the process, but I want that 275 to change randomly each time by +/- 5, 10, or 20. – Ridrex Wafflingham Jul 11 '17 at 10:44
  • `%random% %% 6` returns values from 0 to 5, so it'll never reach `if %num%==6 %ethercost%+=20` – phuclv Jul 11 '17 at 11:20

2 Answers2

2

You need to make use of this:

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
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • You don't _need_ the `%`s around `%ethercost%` in a `set /a` statement -- just the name will do. The OP could also continue to use the `-=`/`+=` operators: e.g. `if %num%==0 set /a ethercost -= 20`. – TripeHound Jul 11 '17 at 11:30
  • @TripeHound you are right, I just tried that and it worked. – Mike Nakis Jul 11 '17 at 11:38
0

In your code you forgot the set /A command and must include the variable name with no percent signs (because %ethercost% is the variable value); that is:

if %num%==0 set /A ethercost-=20

However, this question is an excellent example to introduce a frequently used concept called array. Its usage is so simple that I will not include extensive explanations, just a small comment in the code:

@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

You may read an extensive description of the array concept in this Wikipedia article and a detailed explanation of its use in Batch files at this post.

Aacini
  • 65,180
  • 12
  • 72
  • 108