1

下面代码的输出只是重复“不平衡括号”x100。如果我取出括号并留下 %%i%5 它只是循环数字 1-100 而没有 mod。如果我让它加或减,它工作正常。为什么它找不到mod,特别是?

    :MAIN
     setlocal EnableDelayedExpansion
     set result=0
     for /L %%i in (1,1,100) do (
     set /a result= (%%i%5)
     echo !result!
     )
     endlocal

我还有一些我似乎找不到的问题的代码。如果输入非零数字,它工作得很好。

@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

但是如果第二个数字是 0,它的输出是:

Divide by zero error.
ECHO is off.
Press any key to continue...

当我按下一个键时,程序结束而不是去:错误。我意识到 if 语句存在问题。为什么它说 ECHO 已关闭?有人可以指出我正确的方向吗?

4

1 回答 1

5
 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]

于 2013-03-30T04:01:13.610 回答