html5468
html5468

Reputation: 17

Batch Random Number Generator - Generates Same Number as Before

Basically, what is happening is my code continues to generate the same number. I have turned echo off to see the problem and the actual %random% variable is changing, but it seems like it does the math and says "No, it's really this number." Here's the code:

set /a num=(24 * %random%) / 32768 + 1

I have tested that code by itself and it works fine. However when I add my if statements* to the code, it goes all whack. So, the question is, how do I fix this and why is it happening?

*My if statements:

if "%num%"=="24" (
  echo X
  set /p ans=
  if "%ans%"=="litin" (
    echo.
    echo Correct!
    pause>nul
    goto generate
  )
)

All of my if statements look like that.

Upvotes: 1

Views: 583

Answers (2)

Mustafa
Mustafa

Reputation: 2487

You might want to use EQU for comparing numbers. So try this

if "%num%" EQU 24 ( 
    ...
)

Upvotes: 0

paddy
paddy

Reputation: 63481

Sounds like you might have an issue with variable expansion. Assuming you are doing this stuff in a loop.

Try adding setlocal at the top of your program like this:

setlocal ENABLEDELAYEDEXPANSION

And endlocal at the end of your program:

endlocal

Now, when you need to use a variable that is changing inside a loop, use the ! syntax instead of %:

if "!num!"=="24" (
  echo X
  set /p ans=
  if "!ans!"=="litin" (
    echo.
    echo Correct!
    pause>nul
    goto generate
  )
)

Upvotes: 1

Related Questions