Caniuslupis
Caniuslupis

Reputation: 13

Changing variable inside if blocks in .bat/.cmd programs

I was designing a simple program in .bat (btw, is .bat the same as DOS?) that would have the user guess at the X-value of a quadratic, and I ran into a problem, namely, a missing operand error as indicated by the comment in the code below.

@echo off
setlocal enabledelayedexpansion
:top
set /p q=Take a guess:
if %q% equ 67 (
  echo YOU GOT IT! CONGRATULATIONS! The equation was "Y=17*[X-67]*[X-67]+166"
  pause
  EXIT
)
if NOT %q% equ 67 (
  echo try again.
  ::The problem is definitely in the line below this one.
  set /a r=17*(%q%-67)*(%q%-67)+189
  echo The resulting Y value is %r%
  pause
  goto top
)

What should I change so the program stores the correct value into r?

Upvotes: 1

Views: 101

Answers (2)

user4245152
user4245152

Reputation:

This Works:

@echo off
title written by XLR8 from http://sd-storage.weebly.com
:top
set /p q=Take A Guess
if %q%==67 goto correct
goto incorrect

:correct
echo YOU GOT IT! CONGRATULATIONS! The equation was "Y=17*[X-67]*[X-67]+166"
Echo Press Any Key To Exit
pause >nul
EXIT

:incorrect
echo try again.
goto top

set r=17*(%q%-67)*(%q%-67)+189
echo The resulting Y value is %r%
echo Press Any Key To Start Again
pause >nul
goto top

Upvotes: 0

Magoo
Magoo

Reputation: 79983

Well, logically to reach the if not %q% equ 67 statement, q must be not-67; but fixing that little flaw will disguise the problem.

You have in the if-not-67 statement

if NOT %q% equ 67 (
...
... bad idea to use ::-comments within a block...
set /a r=17*(%q%-67)*(%q%-67)+189
...
...
...
)

The problem is that the first ) in the set statement is closing the if not ...( You'd need to escape both ) in that set with a leading caret each ^)

Your nxt problem will be that since you are setting r within the block [from if not .. 67 ( to goto top ) then you can't access its changed value with %r% but must use !r! - for which you've conveniently use enabledelayedexpansion Well - actually, you could use

call echo The resulting Y value is %%r%%

but much easier to use

echo The resulting Y value is !r!

Upvotes: 2

Related Questions