2

I'm having difficulty with number comparisons like <, >, and == in my Batch code. What Im doing is generating a random number and using that answer to do something, this is what I've written:

set rand=%random%
set rand=%rand:~1,1% 
If %rand%==9 goto nine
If %rand%>5 goto above 5
If %rand%>1 goto above 1
If %rand%==0 goto zero

And the code just closes when I run it. I tried putting space between the two objects being compared and the inequality but it still doesn't work.

Remember, this is Batch code on Windows.

j0k
  • 22,600
  • 28
  • 79
  • 90
Maikeru Konare
  • 21
  • 1
  • 1
  • 5

2 Answers2

7

for if commands use these keys instead of the equal and greater than symbol;

EQU - equal
NEQ - not equal
LSS - less than
LEQ - less than or equal
GTR - greater than
GEQ - greater than or equal

For Equ tho, i would suggest using == instead of equ. easier to type.

EDG
  • 133
  • 1
  • 3
  • 9
5

read HELP IF and then try this

if %rand% equ 9 goto nine
if %rand% gtr 5 goto above5
goto below5

note that the label names cannot contain blanks

as an additional bonus, read HELP SET and change the way you try to obtain the random 0 to 9 number into

set /a rand=%random% %% 10
PA.
  • 28,486
  • 9
  • 71
  • 95
  • 1
    Oh, certainly! read `HELP SET`. Very good advice. There are a couple of traps here. It's unclear whether `set rand=%rand:~1,1%` is intended to get the `FIRST` character of the string. It will in fact get the `SECOND` as substringing uses a ZERO base for the start-position. HOWEVER getting the `FIRST` character will result in a violently-skewed selection. The number-STRING returned by `%random%` is `0`..`32767`. This means that there is only `ONE` result that starts `0` of the 32768 combinations, but there are 11,111 that start `1` and 11,111 that start `2`. – Magoo Apr 04 '13 at 02:36
  • If `set rand=%rand:~1,1%` was deliberately chosen to get the `SECOND` character, which would result in a more even distribution, then for `%RANDOM%`=0..9 (only 10 results of 32768) then `RAND` would be set to [nothing] and that would play havoc with the `IF` statement as the first comparison-string would be empty, upsetting the syntax. Whereas the `set /a...` method would *work* it would be simpler to use `set rand=%rand:~-1%` which returns the `LAST` character of `rand` and amounts to EXACTLY the same thing. OR `set /a rand=%random:~-1%` which saves a step and is simpler still. – Magoo Apr 04 '13 at 02:44
  • correct, I was in doubt to suggest either `%rand:~-1%` or `%random% %% 10` because for the current situation it does not make any differece. But `%random% %% 10` is more flexible. You might change 10 for another number to have a different range (for example, use 6 for uneskewed dice) – PA. Apr 04 '13 at 07:08