Reputation: 35
The output of the code below just repeats "Unbalanced parentheses"x100. If I take out the parentheses and leave %%i%5 it just loops numbers 1-100 without the mod. If I make it add or subtract, it works fine. Why won't it find the mod, specifically?
:MAIN
setlocal EnableDelayedExpansion
set result=0
for /L %%i in (1,1,100) do (
set /a result= (%%i%5)
echo !result!
)
endlocal
I have this other bit of code with a problem I can't seem to find. If nonzero numbers are entered, it works just fine.
@echo off
:MAIN
set /p number1= "Enter 1st number:”
if %number1%== "9" goto second_num
:second_num
set /p number2= “Enter 2nd number:”
if %number2%== “0” goto error
if %number2%== "9" goto division
:division
set /a result= (%number1%/%number2%)
echo %result%
pause
exit
:error
echo "Error. Cannot divide by 0. Start over."
goto MAIN
But if the second number is 0, it's output is:
Divide by zero error.
ECHO is off.
Press any key to continue...
And when I press a key, the program ends instead of going to :error. I realize there's a problem with an if statement. And why does it say ECHO is off? Could someone please point me in the right direction?
Upvotes: 1
Views: 5271
Reputation: 80033
set /a result= (%%i%5)
is your problem. The closing parenthesis is seen by the FOR as its closing parenthesis, so the SET has unbalanced parentheses.
Change the )
in the SET
to ^)
- the caret (^
) escapes the )
telling the processor that it's part of the set
, not of the for
While you're at it, the %5
should be %%5
becaue bizarrely, %
escapes %
, not ^
and the processor needs to be told that the %
isn't part of %5
- the fifth parameter to the batchfile.
The next problem is caused by not understanding that an environment variable is ALWAYS a string. The only time quotes are needed is when it may contain certain characters like SPACES. The statement if %var%==7
is comparing the string contents of var
with the string 7
, hence your statements are comparing the contents of the variable
with "9"
(or whatever). These are NEVER going to be equal. Now - "%number2%"
may be equal, as both of the actual STRINGS may be equal.
If ECHO
has nothing as its "argument" then it reports its state, that is either ON or OFF. SInce RESULT
was not SET because of the error attempting to divide by 0, the statement boils down to ECHO
so the echo state is duly reported.
The cure is to try ECHO.
- the dot gives ECHO
something to chew on and ot'll produce a blank line since %result% is set to [nothing]
Upvotes: 5